简易版,在index.js一个文件中写出来,虽然是简易版的,但是麻雀虽小五脏俱全,该有的功能都在,只是样式稍微不那么好看。
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class App extends Component {
// 状态
state = {
comments: [
// {
// id: 1,
// author: 'zs',
// content: '元旦快乐'
// },{
// id: 2,
// author: 'lisi',
// content: '我要冲刺12k+'
// }
],
// 发帖人
author: '',
// 发帖内容
content: ''
}
// 渲染发帖列表
renderList() {
// 获取comments数据
const { comments } = this.state;
if(comments.length === 0) {
return (
<div>暂无帖子。。。</div>
)
}
// 有帖子信息
return (
<ul>
{
comments.map(item=> <li key={item.id}>
<p>发帖人:{item.author}</p>
<p>发帖内容:{item.content}</p>
</li>)
}
</ul>
)
}
// 表单处理
handleForm = (e)=>{
const {name, value} = e.target;
// 修改状态
this.setState((state)=>{
return {
[name]: value
}
})
}
// 添加帖子
addComment = ()=>{
const { author, content, comments} = this.state;
// 创建新帖
const comment = {
id: Math.random(),
author,
content
}
this.setState({
comments: [comment,...comments],
author: '',
content: ''
})
}
render() {
const {author, content} = this.state;
return (
<div>
<div>
发帖人:<input type="text" name="author" value={author} onChange={this.handleForm} placeholder='请输入发帖人'/><br/>
发帖内容:<textarea name="content" value={content} onChange={this.handleForm} placeholder='请输入内容'/><br/>
<button onClick={this.addComment}>发布</button>
</div>
{this.renderList()}
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'));