![](https://img-blog.csdnimg.cn/direct/9d942d7aa1b94fb4bab767afae8dc70e.png)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'
class Hello extends React.Component {
constructor() {
super()
this.state = {
userName: '',
userContent: '',
comments: [
{
id: 1,
name: 'jack',
content: '12312312'
}
]
}
}
// 渲染列表评论
renderContent() {
if (this.state.comments.length === 0) {
return <h2>暂无评论,抓紧评论吧</h2>
}
return (
<ul>
{
this.state.comments.map(item =>
(<li key={item.id}>
<h2>发表人:{item.name}</h2>
<p>发表内容:{item.content}</p>
</li>
))
}
</ul>
)
}
// 监听输入框和文本框值改变
changeForm = (e) => {
let { name, value } = e.target
this.setState({
[name]: value
})
}
// 发表评论时做出的处理
postComment = () => {
let { userName, userContent, comments } = this.state
if(userName===''||userContent===''){
return alert('请输入评论人和评论内容')
}
// 定义一个新数组,添加到新数组
let newComments = [{
id: Math.random(),
name: userName,
content: userContent,
}, ...comments]
// 将新数组更新给绑定数组
this.setState({
comments: newComments,
userName: '',
userContent: ''
})
}
render() {
let { userName, userContent } = this.state
return (
<div className='div'>
<div>
<input className='userName' type='text' value={userName} name='userName' placeholder='请输入评论人' onChange={this.changeForm}></input>
<br />
<textarea className='userContent' value={userContent} name='userContent' rows={7} placeholder='请输入评论' onChange={this.changeForm}></textarea>
<br />
<button onClick={this.postComment}>发表评论</button>
</div>
{this.renderContent()}
</div>
)
}
}
ReactDOM.render(<Hello />, document.getElementById('root'))
.div{
width: 500px;
padding: 20px;
border: 1px solid #333;
}
.userName {
width: 480px;
height: 25px;
margin-bottom: 10px;
}
.userContent{
width: 480px;
}