效果图:
src结构:
index.html:
index.js:
comment-add.jsx:
comment-item.jsx:
comment-list.jsx:
app.jsx:
import React,{Component} from 'react'
import ReactDOM from 'react-dom'
import CommentAdd from './CommentAdd/comment-add'
import CommentList from './CommentList/comment-list'
export default class App extends Component{
constructor(props){
super(props);
this.state={
comments:[]
};
};
componentDidMount(){
setTimeout(() => {
this.setState({
comments:[
{username:'Tom',content:'React挺好的'},
{username:'Mary',content:'React挺好的'}
]
})
},1000);
}
appTakeData = (comment) => {
let {comments} = this.state;
comments.unshift(comment);//unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度
this.setState({comments});
}
appDeleteData = (index) =>{
console.log(index);
let {comments} = this.state;
comments.splice(index,1);//splice()可以做到增删改
this.setState({comments});
}
render(){
const {comments} = this.state;
return(
<div>
<header className='site-header jumbotron'>
<div className='container'>
<div className='row'>
<div className='col-xs-12'>
<h1>请发表对React的评论</h1>
</div>
</div>
</div>
</header>
<div className='container'>
<CommentAdd appTakeData={this.appTakeData}></CommentAdd>
<CommentList comments={comments} appDeleteData={this.appDeleteData}></CommentList>
</div>
</div>
)
}
}
问题总结