状态提升
当两个以上组件使用同一个数据时,将数据提升到父组件中
数据流向: 父组件传递到子组件中
CommentList.js
import React from 'react'
const CommentList = ({comments})=>{
return(
<div className="comment-list">
<label>评论列表</label>
<ul className="list-group mb-3">
{
comments.map((comment, index) =>
<li key={index} className="list-group-item">{comment}</li>
)
}
</ul>
</div>
)
}
export default CommentList
CommentBox.js
import React from 'react';
class CommentBox extends React.Component{
constructor(props){
super(props)
this.submitHandle = this.submitHandle.bind(this)
}
submitHandle(event){ this.props.onAddComment(this.textInput.value);
event.preventDefault();
}
render() {
return(
<form className="p-5" onSubmit={this.submitHandle}>
<div className="form-group">
<label>留言:</label>
<input ref={ (textInput) => {this.textInput = textInput}}
type="text"
className="form-control"
>
</input>
</div>
<button type="submit" className="btn btn-primary">提交</button>
<p>已有{this.props.commentsLength}条评论</p>
</form>
)
}
}
export default CommentBox
App.js
import CommentBox from './component/CommentBox2'
import CommentList from './component/CommentList'
class App extends Component{
constructor(props){
super(props);
this.state = {
comments: ["this is the first comment","this is the first comment"]
}
this.addComment = this.addComment.bind(this)
}
addComment(comment){
this.setState({
comments: [...this.state.comments, comment]
})
}
render(){
const { comments } = this.state;
return(
<div className="App">
<header className="App-header">
<CommentList comments={comments}></CommentList>
<CommentBox
commentsLength={comments.length}
onAddComment = {this.addComment}
></CommentBox>
</header>
</div>
)
}
}
export default App;