01评论小案例

  0.准备工作:安装脚手架(npx create-react-app pinglun),启动项目(npm start)

  1. 循环用map 判断条件直接写 if

  2. 文本框值 1 先绑定value 2 在onChange值改变的函数 去修改值

  3. 如果 数据是 数组 或者对象 需要先 展开赋值一个新数据 操作新数据 再把新数据去赋值

  4. 修改数据必须 用this.setState({ })

App.js

import React from 'react';
import './App.css'

class App extends React.Component {
  state={
    comment:[
      { id: 1, name: 'jack', content: '沙发!!!' },
      { id: 2, name: 'rose', content: '板凳~' },
      { id: 3, name: 'tom', content: '楼主好人' }
    ],
    username:'',
    content:''
  }

  // 
  renderList=()=>{
    if(this.state.comment.length===0){
      return  <div className="no-comment">暂无评论,快去评论吧~</div>
    }else{
      return  <ul>
      {/* 循环生成数据 */}
      {this.state.comment.map((item)=>{
        return <li key={item.id}>
        <h3>评论人:{item.name}</h3>
        <p>评论内容:{item.content}</p>
      </li>
      })}
    </ul>
    }
  }

  addComment=()=>{
    console.log('ewfwf',this.state.username,this.state.content)
    // 给数组追加一条数据
    let obj={
      id:this.state.comment.length+1,
      name:this.state.username,
      content:this.state.content
    }
    //react中 的数组和对象形式的数据 需要先 赋值成一个最新的数据 操作完成 再把新数据赋值
    let newComment=[...this.state.comment]
    newComment.push(obj)

    // 修改数据要用this.setState({})
    this.setState({
      comment:newComment
    })
  }

  changeName=(e)=>{
    // 把文本框的值给username
    console.log(e.target.value)
    this.setState({
      // 在react中获取表单的值  1.先给input绑定value  2.绑定onChange事件把e.target.value赋值给input中的value的值
      username:e.target.value
    })
  }

  changeContent=(e)=>{
    this.setState({
      content:e.target.value
    })
  }

  render(){
    return (
      <div className="app">
        <div>
          <input value={this.state.username} onChange={this.changeName} type="text" className="user" placeholder="请输入评论人"/>
          <br />
          <textarea value={this.state.content} onChange={this.changeContent} className="content"  rows="10" placeholder="请输入评论内容"/>
          <br/>
          <button onClick={this.addComment}>发表评论</button>
        </div>
   
        {this.renderList()}
      </div>
     )
  }
}

export default App;

App.css

.app {
  width: 300px;
  padding: 10px;
  border: 1px solid #999;
}

.user {
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 10px;
}

.content {
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 10px;
}

.no-comment {
  text-align: center;
  margin-top: 30px;
}

猜你喜欢

转载自www.cnblogs.com/meiqiyuanzi/p/12151771.html