04.React组件基础案例

案例:需求分析

``` 1.渲染评论列表(列表渲染) 2.没有评论数据时渲染:暂无评论(条件渲染) 3.获取评论信息,包括评论人和评论内容(受控组件) 4.发表评论,更新评论列表(setState()) ```

案例:实现步骤

1.渲染评论列表

``` 1.在state 中初始化评论列表数据 2.使用数组的map方法遍历state中的列表数据 3.给每个被遍历的li元素添加key属性 ```

2.渲染暂无评论

``` 1.判断列表数据的长度是否为0 2.如果为0,则渲染暂无评论 ```

3.获取评论信息

``` 1.使用受控组件的方式处理表单元素 ```

4.发表评论

``` 1.给按钮绑定单机事件 2.在事件处理程序中,通过state获取评论信息 3.将评论信息添加到state中,并调用setState()方法更新state 4.边界情况:清🈳️文本框 5.边界情况:非空判断 ``` 完整代码 ``` class App extends React.Component{ //初始化状态 state={ components:[ {id:1,name:'jack',content:'沙发!!!'}, {id:2,name:'rose',content:'板凳'}, {id:3,name:'tom',content:'楼主好人'} ], //评论人 userName:'', //评论内容 userContent:''

}
//渲染评论列表
renderList(){
const {components} = this.state
if(components.length === 0){
return

暂无评论,快去评论吧

}
return(

    {components.map(item=>(

  • 评论人:{item.name}


    评论内容:{item.content}



  • ))}

             </ul>
       )
    

    }
    //处理表单元素值
    handleFrom = e =>{
    const {name,value} = e.target
    this.setState({
    [name]:value
    })
    }
    //发表评论
    addComment = () =>{
    const {components,userName,userContent} = this.state

       //非空校验
       if(userName.trim() ===''|| userContent.trim() ===''){
           alert('请输入评论人和评论内容')
           return
       }
       const newComponents = [{
           id:Math.random(),
           name:userName,
           content:userContent
       },...components]
    
       //文本框的值如何清空?要清空文本框只需要将其对应的state清空即可
       this.setState({
        components:newComponents,
        userName:'',
        userContent:''
       })
    

    }
    render(){
    const {userName,userContent} = this.state
    return(











    {/* 通过条件渲染决定渲染什么内容 */}
    {this.renderList()}

        )
    }
    

    }

posted @ 2020-01-29 22:26  ヾ百毒不侵  阅读(124)  评论(0编辑  收藏  举报