在 本教程系列的前 一部分中,您了解了如何为 react 博客应用程序实现个人资料页面功能。在本教程中,您将了解如何为博客文章实现标签。
入门
让我们从克隆本系列最后一部分的源代码开始。
https://github.com/royagasthyan/ReactBlog-Profile
克隆目录后,导航到项目目录并安装require d 依赖项。
cd ReactBlogApp-Profile npm install
启动节点.js 服务器,您将在 http://localhost:7777/index.html#/运行应用程序。
创建标签页
让我们首先为用户创建一个链接以将标签添加到mongodb数据库。在页面中,为index.html
页面再添加一个。li
Add Tag
<li role="presentation" id="tagHyperlink"><a href="/home#/addTag">Tag</a></li>
当用户单击Add Tag
链接时,它应该显示AddTag
React 组件。所以让我们在文件中为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> ) } }
如上面的代码所示,在AddTag
react 组件类中,您已经为页面呈现了基本的 HTML 模板。在 componentDidMount
方法内部,您具有使AddTag
超链接处于活动状态的类名。
保存上述更改并让服务器恢复正常。登录应用程序并单击“添加标签”链接,您将能够查看该Add Tag
页面。
实现添加标签功能
定义一个状态变量来跟踪标签的变化。
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); }); }
让我们为/addTag
. 在app.js
文件中,创建/addTag
路由,它将解析数据并将数据插入到 MongoDB 数据库中。
app.post('/addtag', function (req, res) { var tag = req.body.tag; post.addTag(tag,function(result){ res.send(result); }); })
在端点内部,您调用了从文件中/addTag
调用的方法。让我们在文件中创建方法。这是它的外观:addTag
post.js
addTag
post.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
页面中填充标签。让我们首先创建一个getTags
在post.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 端点,它将getTag
在app.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
状态变量中设置数据。
在ShowPost
React 组件的 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 元素中。
让我们在下拉列表中添加一个值为 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>
您已向 onChange
select HTML 元素添加了一个事件。这是handleTagChange
事件的样子:
handleTagChange(e){ this.setState({tag:e.target.value}) }
用户选择标签后,该值将在状态变量中可用tag
。
在React 组件 的方法中包含tag
变量。addPost
AddPost
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); }); }
更改/addpost
API 端点以包含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 上获得。