react组件基础综合练习_react.js

import React from "react";

export class Zonghedemo extends React.Component {
constructor() {
super();
this.state = {
comments: [
{ id: 1, name: "jack", content: "沙发" },
{ id: 2, name: "kate", content: "板凳" },
{ id: 3, name: "zhang", content: "一楼" },
],
userName: "",
userContent: "",
};
}
renderList() {
console.log(this); //Zonghedemo 似乎之前讨论的this指向的问题,不复存在,直接写函数,下面直接调用,也没有出现错误
const { comments } = this.state;
if (comments.length === 0) {
return <div>暂无评论,快来评论吧</div>;
} else {
return (
<ul>
{comments.map((item) => {
return (
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
);
})}
</ul>
);
}
// return this.state.comments.length === 0 ? (<div >暂无评论,快来评论吧</div>)
// : ( <ul>
// {this.state.comments.map(item=>
// {
// return (
// <li key={item.id}>
// <h3>评论人:{item.name}</h3>
// <p>评论内容:{item.content}</p>
// </li>
// )
// }
// )}
// </ul>)
}
handleForm = (e) => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
// this.state.userName = "";
// this.state.userContent = "";
};
addComment = ()=> {
const { comments, userName,userContent} = this.state;
if(!userName.trim() || !userContent.trim()) {
alert("请输入评论人名字或输入内容")
}else {
const newComments = [
{id: this.state.comments.length,name:userName,content:userContent },
...comments
];
this.setState({
comments: newComments,
userName: "",
userContent: ""
});
}
};
render() {
// 组件所有的东西,还必须写到一个div里面才行
const { userName, userContent } = this.state;
return (
<div>
<input
type="text"
placeholder="请输入评论人"
onChange={this.handleForm}
value={userName}
name="userName"
/>
<br />
<textarea
placeholder="请输入评论内容"
onChange={this.handleForm}
value={userContent}
name="userContent"
></textarea>
<button onClick={this.addComment}>发表评论</button>
<br />
{this.renderList()}
{/* {this.state.comments.length === 0 ? (<div >暂无评论,快来评论吧</div>)
: ( <ul>
{this.state.comments.map(item=>
{
return (
<li key={item.id}>
<h3>评论人:{item.name}</h3>
<p>评论内容:{item.content}</p>
</li>
)
}
)}
</ul>)
} */}
</div>
);
}
}