```html
import React from "react";
class CommentList extends React.Component {
state = {
comments: [
// { id: 1, name: 'shi', content: '沙发' },
// { id: 2, name: 'xiao', content: '板凳' },
// { id: 3, name: 'hua', content: '地板' }
],
userName:'',
userContext:''
}
renderList() {
const {comments}= this.state
if (comments.length === 0) {
return (
暂无评论
)
}
return (
{
comments.map(item => (
-
评论人:{item.name}
评论:{item.content}
))
}
)
// return this.state.comments.length === 0 ? (暂无评论
) :
// (
// {
// this.state.comments.map(item => (
// -
//
评论人:{item.name}
// 评论:{item.content}
//
// ))
// }
//
)
}
handleForm=(e)=>{
const {name,value}= e.target
this.setState({
[name]:value
})
}
addComment=()=>{
const {comments,userName,userContext}= this.state
// 非空校验
if(userName.trim()===""||userContext.trim()===""){
alert('请输入评论内容')
return
}
const newComments = [{
id:Math.random(),
name:userName,
content:userContext
},...comments]
this.setState({
comments:newComments,
// 清空文本空
userContext:'',
userName:''
})
}
render() {
const {userName,userContext}= this.state
return (
{/* {this.state.comments.length === 0 ? (
暂无评论
) :
(
{
this.state.comments.map(item => (
-
评论人:{item.name}
评论:{item.content}
))
}
)
} */}
{this.renderList()}
)
}
}
export default CommentList
```