gpt4 book ai didi

javascript - 将状态从 childComp 传输到 ParentComp

转载 作者:行者123 更新时间:2023-11-28 17:54:01 24 4
gpt4 key购买 nike

我有两个组件,我需要将state从子组件传输到父组件

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,它需要两个参数文本和日期,总之,当我单击按钮时我需要传输statechildCompparentComp,然后在 parentComp 中创建具有两个参数的操作。那么我怎样才能做到这一点呢?

最佳答案

Refer component communication

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com