边界问题
//导入react
import React from 'react'
import ReactDOM from 'react-dom'
//导入组件
// 约定1:类组件必须以大写字母开头
// 约定2:类组件应该继承react.component父类 从中可以使用父类的方法和属性
// 约定3:组件必须提供render方法
// 约定4:render方法必须有返回值
class HelloWorld extends React.Component {
//初始化状态
state = {
comments: [
{
id: 1,
name: 'geyao',
content: '哈哈',
},
{
id: 2,
name: 'fangfang',
content: '哈哈',
},
{
id: 3,
name: 'geyao',
content: '哈哈',
},
],
userName: '',
userContent: '',
}
//修改表单元素
handleForm = (e) => {
const { name, value } = e.target
this.setState({
[name]: value,
})
}
//添加信息
addComment=()=>{
const { comments,userName, userContent } = this.state
const newComents=[{
id:Math.random(),
name:userName,
content:userContent
},...comments]
if(userName.trim()===""||!userContent.trim()===""){
alert("评论人和评论列表不能为空")
return false
}
this.setState({
comments:newComents,
userContent:"",
userName:""
})
}
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}
></textarea>
<br />
<button onClick={this.addComment}>发表评论</button>
</div>
{this.state.comments.length === 0 ? (
<div className="no-comment">暂无评论,快去评论吧~</div>
) : (
<ul>
{/* <li>
<h3>评论人:jack</h3>
<h3>评论内容:沙发</h3>
</li> */}
{this.state.comments.map((item) => (
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
))}
</ul>
)}
</div>
)
}
}
ReactDOM.render(<HelloWorld />, document.getElementById('root'))
运行结果