1. 需求分析
渲染评论列表(列表渲染)
没有评论数据时渲染:暂无评论(条件渲染)
获取评论信息,包括评论人和评论内容(受控组件)
发表评论,更新评论列表( setState() )
2.实现步骤
2.1.渲染评论列表
在 state 中初始化评论列表数据
使用数组的 map 方法遍历 state 中的列表数据
给每个被遍历的 li 元素添加 key 属性
import React from "react"
import ReactDOM from "react-dom"
import "./index.css"
class Test extends React. Component {
state = {
comments: [
{
id: 1 , name: "keinee" , content: "今天不学习,明天变垃圾" } ,
{
id: 2 , name: "kei" , content: "今天不学习" } ,
{
id: 3 , name: "nee" , content: "明天变垃圾" } ,
] ,
}
render ( ) {
return (
< div className= 'app' >
< div>
< input
className= 'user'
type= 'text'
placeholder= '请输入用户名'
/ >
< br / >
< textarea
className= 'content'
cols= '30'
rows= '10'
placeholder= '请输入内容'
/ >
< br / >
< button> 发送< / button>
< / div>
< div className= 'no-comment' > 暂无评论,快来发表第一条评论吧< / div>
< ul>
{
}
{
this . state. comments. map ( ( item ) => (
< li key= {
item. id} >
< h3> 评论人:{
item. name} < / h3>
< p> 评论内容:{
item. content} < / p>
< / li>
) ) }
< / ul>
< / div>
)
}
}
ReactDOM. render ( < Test / > , document. getElementById ( "root" ) )
//index.css
body {
margin : 0;
font-family : -apple-system, BlinkMacSystemFont, "Segoe UI" , "Roboto" ,
"Oxygen" , "Ubuntu" , "Cantarell" , "Fira Sans" , "Droid Sans" ,
"Helvetica Neue" , sans-serif;
-webkit-font-smoothing : antialiased;
-moz-osx-font-smoothing : grayscale;
}
code {
font-family : source-code-pro, Menlo, Monaco, Consolas, "Courier New" ,
monospace;
}
.app {
float : left;
border : 1px solid #000;
padding : 10px;
}
.user {
margin : 5px;
width : 290px;
}
.content {
width : 290px;
margin : 5px;
}
.no-comment