案例说明:发表评论人和评论内容,并展示;
有评论时:(展示评论内容)
无评论时:(展示暂无评论)
//创建一个组件
import React from 'react';
class Thrus extends React.Component {
state = {
txt: '',
content: '',
songs: [
// {
// id: 1, name: 'qqq', unname: 'ddd'
// },
// {
// id: 2, name: 'qqq', unname: 'ddd'
// },
// {
// id: 3, name: 'qqq', unname: 'ddd'
// }
],
nextid: 4
}
handleChange = (e) => {
const target = e.target;
const name = target.name;
const value = target.value;
this.setState({
[name]: value
})
}
handleSend = () => {
if (this.state.txt === '' || this.state.content === '') {
alert('请输入评论人和评论内容')
return false;
}
const comment = this.state.songs;
comment.push({
id: this.state.nextid,
name: this.state.txt,
unname: this.state.content
})
this.state.nextid++
this.setState({
nextid: this.state.nextid,
songs: comment
})
this.state.txt = '';
this.state.content = '';
}
handleShow = () => {
if (this.state.songs.length !== 0) {
return (
<div>
<ul>
{this.state.songs.map(item =>
<li key={item.id}>
<p>评论人:{item.name}</p>
<p>评论内容:{item.unname}</p>
</li>
)}
</ul>
</div>
)
}
return <div>暂无评论</div>
}
render() {
return (
<div>
<input placeholder='评论人' value={this.state.txt} type='text' name='txt' onChange={this.handleChange} /><br />
<textarea value={this.state.content} type='text' name='content' onChange={this.handleChange} placeholder='评论内容' ></textarea>
<br />
<button onClick={this.handleSend}>发送</button><br />
<div>{this.handleShow()}</div>
</div>
)
}
}
//导出
export default Thrus;
上述代码为一个评论组件;