React.js 小书 Lesson16 - 实战分析:评论功能(三)
React.js 小书 Lesson16 - 实战分析:评论功能(三)
转载请注明出处,保留原文链接以及作者信息 在线阅读:http://huziketang.com/books/react 接下来的代码比较顺理成章了。修改 // CommentList.js import React,{ Component } from 'react' class CommentList extends Component { render() { const comments = [ {username: 'Jerry',content: 'Hello'},{username: 'Tomy',content: 'World'},{username: 'Lucy',content: 'Good'} ] return ( <div>{comments.map((comment,i) => { return ( <div key={i}> {comment.username}:{comment.content} </div> ) })}</div> ) } } export default CommentList 这里的代码没有什么新鲜的内容,只不过是建立了一个
修改 import React,{ Component } from 'react' class Comment extends Component { render () { return ( <div className='comment'> <div className='comment-user'> <span>{this.props.comment.username} </span>: </div> <p>{this.props.comment.content}</p> </div> ) } } export default Comment 这个组件可能是我们案例里面最简单的组件了,它只负责每条评论的具体显示。你只需要给它的 马上把 import React,{ Component } from 'react' import Comment from './Comment' class CommentList extends Component { render() { const comments = [ {username: 'Jerry',content: 'Good'} ] return ( <div> {comments.map((comment,i) => <Comment comment={comment} key={i} />)} </div> ) } } export default CommentList 可以看到测试数据显示到了页面上:
之前我们说过 import React,{ Component } from 'react' import Comment from './Comment' class CommentList extends Component { render() { return ( <div> {this.props.comments.map((comment,i) => <Comment comment={comment} key={i} /> )} </div> ) } } export default CommentList 这时候可以看到浏览器报错了:
这是因为 class CommentList extends Component { static defaultProps = { comments: [] } ... 这时候代码就不报错了。但是 我们在 import React,{ Component } from 'react' import CommentInput from './CommentInput' import CommentList from './CommentList' class CommentApp extends Component { constructor () { super() this.state = { comments: [] } } handleSubmitComment (comment) { console.log(comment) } render() { return ( <div className='wrapper'> <CommentInput onSubmit={this.handleSubmitComment.bind(this)} /> <CommentList comments={this.state.comments}/> </div> ) } } export default CommentApp 接下来,修改 ... handleSubmitComment (comment) { this.state.comments.push(comment) this.setState({ comments: this.state.comments }) } ... 现在代码应该是可以按照需求正常运作了,输入用户名和评论内容,然后点击发布:
为了让代码的健壮性更强,给 ... handleSubmitComment (comment) { if (!comment) return if (!comment.username) return alert('请输入用户名') if (!comment.content) return alert('请输入评论内容') this.state.comments.push(comment) this.setState({ comments: this.state.comments }) } ... 到这里,我们的第一个实战案例——评论功能已经完成了!完整的案例代码可以在这里 comment-app 找到, 在线演示 体验。 总结在这个案例里面,我们除了复习了之前所学过的内容以外还学习了新的知识点。包括:
当然,在真实的项目当中,这个案例很多地方是可以优化的。包括组件可复用性方面(有没有发现其实 到此为止,React.js 小书的第一阶段已经结束,你可以利用这些知识点来构建简单的功能模块了。但是在实际项目如果要构建比较系统和完善的功能,还需要更多的 React.js 的知识还有关于前端开发的一些认知来协助我们。接下来我们会开启新的一个阶段来学习更多关于 React.js 的知识,以及如何更加灵活和熟练地使用它们。让我们进入第二阶段吧! 下一节中我们将介绍《React.js 小书 Lesson17 - 前端应用状态管理 —— 状态提升)》。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |