将评论和暂无评论渲染到评论列表中并优化代码,如图:
首先将数据存储到state中:
state = {
comments: [
{id:1,name:'zzf',value:'妹妹好阔爱啊!!!'},
{id:2, name:'zjl', value:'周董的歌好好听啊!!!'},
{id:3,name:'hg',value:'胡歌演技贼好!!!'}
]}
然后写一个函数来实现渲染:renderList(){
const {comments} = this.state
//判断评论列表长度是否为零,若为零则渲染暂无评论
if(comments.length === 0){
return <div>暂无评论,快去评论吧~</div>
}
return(
<ul>
{comments.map(item => (
<li key = {item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.value}</p>
</li>
</ul>
)
}
在render里面调用这个函数:
render() {
const { userComt,userName} = this.state
return(
<div className='box'>
<div className='box1'>
<input type='text' value={userName} name='userName' onChange={ this.changeForm}/>
<textarea rows='10' cols='30' value={userComt} name='userComt' onChange={ this.changeForm}></textarea>
<button onClick={ this.change}>发表评论</button>
</div>
{ this.renderList()}
</div>
)
}
}
第二步:获取评论信息
changeForm = (e) => {
const {name.value} = e.target
this.setState({
[name]:value
})
在文本框中调用该函数
第三步:发表评论
addContent = () => {
const {comments,userComt,userName} = this.state
//校验是否为空
if(userComt.trim() === '' || userName.trim() === ''){
alert('请输入内容')
return//阻止函数继续执行
}
const newComments = [
{
id:Math.random(),
name:userName,
value:userComt
},
...comments
]
this.setState({
comments:newComments
//清除文本内容
userName:' '
userComt:' '
})
}