// //导入包 import React from 'react' import ReactDOM from 'react-dom'
class App extends React.Component{ state={ //数据 comments:[ {id:1,name:'mama hen',content:'gagagagaga'}, {id:2,name:'doudou',content:'6666'}, {id:3,name:'bear',content:'wawawawawa'} ], userName:'', userContent:'' } renderList(){ //条件渲染 if(this.state.comments.length===0){ return <div className='no comment'>暂无评论</div> } return ( <ul> {this.state.comments.map(item=>( <li key={item.id}> <h3>评论人:{item.name}</h3> <p>内容:{item.content}</p> </li> ) ) } </ul> ) } handleForm=(e)=>{ const{name,value}=e.target this.setState({ [name]:value }) } addComment=()=>{ const {comments,userName,userContent}=this.state const newComments=[ { id:comments.length+1, name:userName, content:userContent }, ...comments ] this.setState({ comments:newComments }) } render(){ return( <div className="app"> <div> <input className='user' type='text' placeholder='请输入名字' value={this.state.userName} onChange={this.handleForm} name='userName'></input> <br/> <textarea className='content' cols='30' rows='10' placeholder='请输入评论' value={this.state.userContent} onChange={this.handleForm} name='userContent'> </textarea> <br/> <button onClick={this.addComment}>发表评论</button> </div>
{this.renderList()} </div>
) } }
//渲染元素 ReactDOM.render(<App/>,document.getElementById('root')) 标签:content,name,comments,react,案例,state,评论,id From: https://www.cnblogs.com/doudou666/p/17134164.html