• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

使用React创建博客应用第6部分:标签

在 本教程系列的前 一部分中,您了解了如何为 react 博客应用程序实现个人资料页面功能。在本教程中,您将了解如何为博客文章实现标签。

入门

让我们从克隆本系列最后一部分的源代码开始。

https://github.com/royagasthyan/ReactBlog-Profile

克隆目录后,导航到项目目录并安装require d 依赖项。

cd ReactBlogApp-Profile
npm install

启动节点.js 服务器,您将在 http://localhost:7777/index.html#/运行应用程序。

创建标签页

让我们首先为用户创建一个链接以将标签添加到mongodb数据库在页面中,index.html页面再添加一个liAdd Tag

<li role="presentation" id="tagHyperlink"><a href="/home#/addTag">Tag</a></li>

当用户单击Add Tag链接时,它应该显示AddTagReact 组件。所以让我们在文件中为Add Tag组件添加一个路由。home.jsx

<Route component={AddTag} path="/addTag"></Route>

这是完整的路线列表:

Reactdom.render(
    <Router history={hashHistory}>
        <Route component={Showpost} path="/"></Route>
        <Route component={AddPost} path="/addPost(/:id)"></Route>
        <Route component={ShowProfile} path="/showProfile"></Route>
        <Route component={AddTag} path="/addTag"></Route>
    </Router>,
document.getElementById('app'));

让我们创建AddTag将在用户单击“添加标签”链接时呈现的组件。 

class AddTag extends React.Component {    constructor(props) {
      super(props);
    }
    
    componentDidMount(){
      document.getElementById('addHyperLink').className = "";
      document.getElementById('homeHyperlink').className = "";
      document.getElementById('profileHyperlink').className = "";
      document.getElementById('tagHyperlink').className = "active";
    }
    
    render() {
      return (
        <div className="col-md-5">
          <div className="form-area">  
              <form role="form">
                <br styles="clear:both" />
                <div className="form-group">
                  <input type="text" className="form-control" id="tag" name="tag" placeholder="Tag" required />
                </div>
                <div className="form-group">
                  <button type="button" id="submit" name="submit" className="btn btn-primary pull-right">Add Tag</button>
                </div>
              </form>

          </div>
        </div>
      )
    }
}

如上面的代码所示,在AddTagreact 组件类中,您已经为页面呈现了基本的 HTML 模板。在 componentDidMount方法内部,您具有使AddTag 超链接处于活动状态的类名。

保存上述更改并服务器恢复正常。登录应用程序并单击“添加标签”链接,您将能够查看该Add Tag页面。

使用React创建博客应用第6部分:标签  第1张

实现添加标签功能

定义一个状态变量来跟踪标签的变化。

constructor(props) {
  super(props);
  this.state = {
    tag:''
  };
}

将标记状态变量附加到渲染方法中的输入元素。

<input value={this.state.tag} type="text" onChange={this.handleTagChange} 
className="form-control" id="tag" name="tag" placeholder="Tag" required />

如上面的代码所示,您还向输入附加了一个onChange 事件以跟踪其值的变化。在构造函数中绑定onChange方法。handleTagChange

constructor(props) {
  super(props);
  this.handleTagChange = this.handleTagChange.bind(this);
  this.state = {
    tag:''
  };
}

现在让我们在React 组件中定义handleTagChange方法。AddTag

handleTagChange(e){
  this.setState({tag:e.target.value})
}

当用户单击 Add 按钮添加标签时,您需要保存数据。因此,让我们将一个 onClick事件附加到输入按钮。

<button type="button" onClick={this.addTag} id="submit" name="submit" className="btn btn-primary pull-right">Add Tag</button>

addTag在 React 组件构造函数中绑定方法并定义方法以对 node.js 服务器端点进行api调用。

constructor(props) {
  super(props);
  this.addTag = this.addTag.bind(this);
  this.handleTagChange = this.handleTagChange.bind(this);
  this.state = {
    tag:''
  };
}

接下来让我们定义addTag使 API 调用到 /addtag端点的方法。

addTag(){

  axios.post('/addtag', {
    tag: this.state.tag
  })
  .then(function (response) {
    console.log('reponse from add tag is ',response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

让我们为/addTagapp.js文件中,创建/addTag路由,它将解析数据并将数据插入到 MongoDB 数据库中。

app.post('/addtag', function (req, res) {
  var tag = req.body.tag;
  post.addTag(tag,function(result){
    res.send(result);
  }); 
})

在端点内部,您调用了文件中/addTag调用的方法。让我们在文件中创建方法这是它的外观:addTagpost.jsaddTagpost.js

addTag: function(tagName, callback){
	MongoClient.connect(url, function(err, db) {
	  	db.collection('tag').insertOne( {
			"name": tagName
		},function(err, result){
			assert.equal(err, null);
	    	console.log("Saved the tag details.");
	    	if(err == null){
	    		callback(true)
	    	}
	    	else{
	    		callback(false)
	    	}
		});
	});
}

从上面的代码中可以看出,您已经习惯MongoClient了连接到 MongoDB 数据库。您已将标记数据插入到数据库中称为标记的集合中。一旦插入数据而没有任何错误,布尔值 true 将传递给回调函数。如果遇到错误,则将布尔值 false 返回给回调函数。

保存上述更改并重新启动服务器。登录应用程序并单击添加标签链接。输入标签名称并单击添加按钮。检查浏览器控制台,您应该能够看到浏览器控制台中记录的成功消息。 

在添加帖子页面上填充标签

Add Tag页面添加标签后,需要在Add post页面中填充标签。让我们首先创建一个getTagspost.js文件中调用的方法,该方法将连接到 MongoDB 数据库并获取标签。这是它的外观:

getTag: function(callback){
	MongoClient.connect(url, function(err, db){
		 db.collection('tag', function (err, collection) {
	        collection.find().toArray(function (err, list) {
	            callback(list);
	        });
	     });
	})
}

如上面的代码所示,您已经使用 MongoClient 连接到 MongoDB 数据库。获取集合后,使用该方法将其转换为数组toArray,然后传递给回调函数。 

接下来创建 Node.js API 端点,它将getTagapp.js

app.post('/gettag', function (req, res) {
  post.getTag(function(result){
    res.send(result);
  });
})

在 组件home.jsx内的文件中AddPost,创建一个调用的方法,该方法getTags/gettag调用 API 并获取标签列表。 

getTags(){
  var self = this;
  
  axios.post('/getTag', {
  })
  .then(function (response) {
    if(response){
      self.setState({tags:response.data}); 
    }
    
  })
  .catch(function (error) {
    console.log('error is ',error);
  });

}

从 API 获取数据后,在tags状态变量中设置数据。

ShowPostReact 组件的 render 方法中,添加 select HTML 元素以绑定tags状态变量。这是它的外观:

<div className="form-group">
  <label for="sel1">Select Tag:</label>
  
  <select className="form-control" >
  {
    this.state.tags.map(function(tag, i) {
      return (<option key={i} value={tag._id}>{tag.name}</option>)       
    }.bind(this))
  }
  </select>
</div>

如上面的代码所示,您已使用该map方法将tags状态变量映射到选择元素。

componentDidMount方法内部,调用该getTags方法以在组件安装后加载标签。

componentDidMount(){
    document.getElementById('addHyperLink').className = "active";
    document.getElementById('homeHyperlink').className = "";
    document.getElementById('profileHyperlink').className = "";
    document.getElementById('tagHyperlink').className = "";
    this.getPostWithId();
    this.getTags();
}

保存上述更改并重新启动服务器。加载Add Post页面后,您应该将标签加载到选择的 HTML 元素中。

使用React创建博客应用第6部分:标签  第2张

让我们在下拉列表中添加一个值为 0 的默认选项。

<div className="form-group">
  <select className="form-control" value={this.state.tag} onChange={this.handleTagChange}>
  <option value="0">Select Tag</option>
  {

    this.state.tags.map(function(tag, i) {
      return (<option key={i} value={tag._id}>{tag.name}</option>)       
    }.bind(this))
  }
  </select>
</div>

您已向 onChangeselect HTML 元素添加了一个事件。这是handleTagChange事件的样子:

handleTagChange(e){
  this.setState({tag:e.target.value})
}

用户选择标签后,该值将在状态变量中可用tag。 

在React 组件 的方法中包含tag变量。addPostAddPost

addPost(){

  axios.post('/addPost', {
    title: this.state.title,
    subject: this.state.subject,
    tag: this.state.tag,
    id: this.props.params.id
  })
  .then(function (response) {
    console.log('response from add post is ',response);
    hashHistory.push('/')
  })
  .catch(function (error) {
    console.log(error);
  });
}

更改/addpostAPI 端点以包含tag参数。

app.post('/addpost', function (req, res) {
  var title = req.body.title;
  var subject = req.body.subject;
  var tag = req.body.tag;
  var id = req.body.id;
  console.log('id is ',id);
  if(id == '' || id == undefined){
    console.log('add');
    post.addPost(title, subject ,tag,function(result){
      res.send(result);
    }); 
  }
  else{
    console.log('update',title,subject);
    post.updatePost(id, title, subject ,tag,function(result){
      res.send(result);
    }); 
  }
  
})

修改文件中的addPost方法post.js以包含tag参数。

addPost: function(title, subject,tag, callback){
	MongoClient.connect(url, function(err, db) {
	  	db.collection('post').insertOne( {
			"title": title,
			"subject": subject,
			"tag": tag
		},function(err, result){
			assert.equal(err, null);
	    	console.log("Saved the blog post details.");
	    	if(err == null){
	    		callback(true)
	    	}
	    	else{
	    		callback(false)
	    	}
		});
	});
}

修改getPostWithId获取帖子详细信息时设置下拉的方法。

getPostWithId(){
  var id = this.props.params.id;
  
  var self = this;
  
  axios.post('/getPostWithId', {
    id: id
  })
  .then(function (response) {
    if(response){
      self.setState({title:response.data.title});
      self.setState({subject:response.data.subject});
      self.setState({tag:response.data.tag})  
    }
    
  })
  .catch(function (error) {
    console.log('error is ',error);
  });

}

保存上述更改并重新启动服务器。登录并导航到“添加帖子” 页面并添加带有选定标签的帖子。您将保存并列出新帖子。单击编辑按钮以编辑帖子详细信息和标签。 

把它包起来

在本教程中,您了解了如何实现添加标签页面。您将标签字段与标题和主题字段一起添加到添加帖子页面。 

希望您喜欢本教程系列。请在下面的评论中告诉我们您的想法、建议或任何更正。

本教程的源代码可在GitHub 上获得。


文章目录
  • 入门
  • 创建标签页
  • 实现添加标签功能
  • 在添加帖子页面上填充标签
  • 把它包起来