我一直在努力寻找一种方法,每次点击按钮,都会在屏幕上添加一个新帖子(种类)。我有新的反应,并不是很了解。该函数确实有效,而console.log()却没有返回Post组件;
export default class Extra extends React.Component {
constructor() {
super();
this.state = {
val :'',
posts: []
}
}
handlePost = () => {
const newPost = <Post status = "Status" about = "This post is about React"></Post>;
this.state.posts.push(newPost);
console.log(this.state.posts.length);
return (this.state.posts[this.state.posts[this.state.posts.length-1]]);
}
render() {
return(
<div>
<button onClick = {this.handlePost}className = "fixed">Post</button>
</div>
);
}
}
const Post = ({ status, about }) => {
return(
<div className = "UI">
<h2>{status}</h2><hr/><br/>
<p>{about}</p>
</div>
);
}
export default Post;
答案 0 :(得分:1)
export default class Extra extends React.Component {
constructor() {
super();
this.state = {
val :'',
posts: []
}
}
handlePost = () => {
const newPost = <Post status = "Status" about = "This post is about React"></Post>;
this.setState({posts:[...this.state.posts,newPost]});
console.log(this.state.posts.length);
}
render() {
return(
<div>
<button onClick = {this.handlePost}className = "fixed">Post</button>
</div>
);
}
}
const Post = ({ status, about }) => {
return(
<div className = "UI">
<h2>{status}</h2><hr/><br/>
<p>{about}</p>
</div>
);
}
export default Post;