1,创建新的react应用
npx create-react-app <项目名称>
运行项目
cd <项目名称>
npm start
2,删除App.js原生App组件代码
3,实现评论列表:
——渲染基础列表页
——初始化state列表数据
——利用受控组件获取输入的表单元素value
——将value值添加至state列表数据中,setState更新状态
——功能完善(发表评论后清空表单数据,若表单值为空则不发表,alert提示消息)
class App extends React.Component{
state = {
comments:[
// { id: 1, name: 'jack', content: '沙发!!!' },
// { id: 2, name: 'rose', content: '板凳~' },
// { id: 3, name: 'tom', content: '楼主好人' }
],
userName:'',
userContent:''
}
//渲染评论列表
renderList(){
const {comments} = this.state;
if(comments.length == 0){
return <div className="no-comment">暂无评论,快去评论吧~</div>
}
return (
<ul>
{
comments.map(item=>(
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
))
}
</ul>
)
}
//发表评论
addComment=()=>{
const {comments,userName,userContent} = this.state;
if(userName !=="" && userContent !==""){
const newComments = [
{id:Math.random(),
name:userName,
content:userContent
},
...comments
]
this.setState({
comments:newComments,
userName:'',
userContent:''
})
}
else{
alert("请输入用户名和内容再发表!");
return
}
}
handleForm=(e)=>{
const {name,value} = e.target;
this.setState(
{[name]:value},
)
}
render(){
const {userName,userContent} = this.state;
return (
<div className="app">
<div>
<input className="user" type="text" placeholder="请输入评论人" value={userName} name="userName" onChange={this.handleForm}/>
<br />
<textarea
className="content"
cols="30"
rows="10"
placeholder="请输入评论内容"
value={userContent}
name="userContent"
onChange={this.handleForm}
/>
<br />
<button onClick={this.addComment}>发表评论</button>
</div>
{this.renderList()}
</div>
);
}
}
app.css样式表所示
.app {
width: 300px;
padding: 10px;
border: 1px solid #999;
}
.user {
width: 100%;
box-sizing: border-box;
margin-bottom: 10px;
}
.content {
width: 100%;
box-sizing: border-box;
margin-bottom: 10px;
}
.no-comment {
text-align: center;
margin-top: 30px;
}