这里的代码没有什么新鲜的内容,只不过是建立了一个 comments 的数组来存放一些测试数据的内容,方便我们后续测试。然后把 comments 的数据渲染到页面上,这跟我们之前讲解的章节的内容一样——使用 map 构建一个存放 JSX 的数组。就可以在浏览器看到效果:

    修改 Comment.js 让它来负责具体每条评论内容的渲染:

    1. import React, { Component } from 'react'
    2. class Comment extends Component {
    3. render () {
    4. return (
    5. <div className='comment'>
    6. <div className='comment-user'>
    7. <span>{this.props.comment.username} </span>:
    8. </div>
    9. <p>{this.props.comment.content}</p>
    10. </div>
    11. )
    12. }
    13. }
    14. export default Comment

    这个组件可能是我们案例里面最简单的组件了,它只负责每条评论的具体显示。你只需要给它的 props 中传入一个 comment 对象,它就会把该对象中的 usernamecontent 渲染到页面上。

    马上把 Comment 应用到 CommentList 当中,修改 CommentList.js 代码:

    可以看到测试数据显示到了页面上:

    之前我们说过 CommentList 的数据应该是由父组件 CommentApp 传进来的,现在我们删除测试数据,改成从 props 获取评论数据:

    1. import React, { Component } from 'react'
    2. import Comment from './Comment'
    3. class CommentList extends Component {
    4. render() {
    5. <div>
    6. <Comment comment={comment} key={i} />
    7. )}
    8. </div>
    9. )
    10. }
    11. }
    12. export default CommentList

    这时候可以看到浏览器报错了:

    React.js 小书实战之评论功能图片

    这是因为CommentApp 使用 CommentList 的时候并没有传入 comments。我们给 CommentList 加上 defaultProps 防止 comments 不传入的情况:

    这时候代码就不报错了。但是 CommentInputCommentApp 传递的评论数据并没有传递给 CommentList,所以现在发表评论时没有反应的。

    我们在 CommentAppstate 中初始化一个数组,来保存所有的评论数据,并且通过 props 把它传递给 CommentList。修改 CommentApp.js

    1. import React, { Component } from 'react'
    2. import CommentInput from './CommentInput'
    3. import CommentList from './CommentList'
    4. class CommentApp extends Component {
    5. constructor () {
    6. super()
    7. this.state = {
    8. comments: []
    9. }
    10. }
    11. handleSubmitComment (comment) {
    12. console.log(comment)
    13. render() {
    14. return (
    15. <div className='wrapper'>
    16. <CommentInput onSubmit={this.handleSubmitComment.bind(this)} />
    17. <CommentList comments={this.state.comments}/>
    18. </div>
    19. )
    20. }
    21. }
    22. export default CommentApp

    现在代码应该是可以按照需求正常运作了,输入用户名和评论内容,然后点击发布:

    为了让代码的健壮性更强,给 handleSubmitComment 加入简单的数据检查:

    1. ...
    2. handleSubmitComment (comment) {
    3. if (!comment) return
    4. if (!comment.username) return alert('请输入用户名')
    5. if (!comment.content) return alert('请输入评论内容')
    6. this.state.comments.push(comment)
    7. this.setState({
    8. comments: this.state.comments
    9. })
    10. }
    11. ...

    到这里,我们的第一个实战案例——评论功能已经完成了!完整的案例代码可以在这里 comment-app 找到, 体验。

    在这个案例里面,我们除了复习了之前所学过的内容以外还学习了新的知识点。包括:

    • 实现功能之前先理解、分析需求,划分组件。并且掌握划分组件的基本原则——可复用性、可维护性。
    • 组件之间使用 props 通过父元素传递数据的技巧。 当然,在真实的项目当中,这个案例很多地方是可以优化的。包括组件可复用性方面(有没有发现其实 CommentInput 中有重复的代码?)、应用的状态管理方面。但在这里为了给大家总结和演示,实现到这个程度也就足够了。