我有两个组件
,我需要将stat
e从子组件
传输到父组件
class Parent Component {
this.state = {text: hahaha}
this.props.action(text, data)
<Children Component />
<button onClick={this.props.action(text, data)}
}
class Children Component {
this.state = {date: 12.12.12}
}
另一个小技巧是我在父组件中有redux-action
,它需要两个参数文本和日期
,总之,当我单击按钮时我需要传输state
从 childComp
到 parentComp
,然后在 parentComp
中创建具有两个参数的操作。那么我怎样才能做到这一点呢?
最佳答案
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
content: 'initial'
}
this.updateParentState = this.updateParentState.bind(this);
}
updateParentState(content){
this.setState({
content: content
})
}
render(){
let { content } = this.state;
return <div>
<Child updateParentState={this.updateParentState}/>
<h1>{ content }</h1>
</div>
}
}
class Child extends React.Component{
constructor(props){
super(props);
this.state = {
value: 'initial'
}
this.handleParentState = this.handleParentState.bind(this);
this.changeContent = this.changeContent.bind(this);
}
handleParentState(content){
let { updateParentState } = this.props;
let { value } = this.state;
updateParentState(content);
}
changeContent(event){
this.setState({
value: event.target.value
})
}
render(){
let { value } = this.state
return <div>
<input value={value} onChange={this.changeContent}/>
<button onClick={this.handleParentState}>Update Parent State</button>
</div>
}
}
关于javascript - 将状态从 childComp 传输到 ParentComp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869155/