gpt4 book ai didi

javascript - react : How to pass values from grandchild through child to parent?

转载 作者:行者123 更新时间:2023-11-28 03:52:28 25 4
gpt4 key购买 nike

我有一个父组件、子组件和孙组件。我有不同的输入字段,想要将值从孙子传递到子子再到父子,最终我用这些值设置状态。我没有包含我的所有代码,但是这样做是必要的,因为我的代码中还有其他内容,我没有将这些内容包含在这篇文章中,因为它不相关。我不确定如何做到这一点,并尝试实现我在网上找到的内容,但是,它不起作用。有任何想法吗?谢谢!!

class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
input: {}
};
this.changeName = this.changeName.bind(this);
this.handleInput = this.handleInput.bind(this);
}

changeName(newName) {
this.setState({
name: newName
});
}
handleInput() {
console.log("helloooooo", this.state.name)
}

render() {
return (
<div>
<Child onChange={this.changeName} onClick={this.handleInput}/>
</div>
)
}
}

class Child extends React.Component {

constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleInput2 = this.handleInput2.bind(this);
}

handleChange(e) {
this.props.handleChange(e);
}

handleInput2() {
this.props.onClick()
}

render() {
return (
<div>
<GrandChild onChange={this.handleChange}/>
<input type="submit" onClick={this.handleInput2}/>
</div>
)
}
}

class GrandChild extends React.Component {

constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleInput2 = this.handleInput2.bind(this);
}

handleChange(e) {
const input = this.props.input;
input[name] = e.target.value;
}

render() {
return (
<div>
<input name="firstname" onChange={this.handleChange}/>
<input name="lastname" onChange={this.handleChange}/>
</div>
)
}

最佳答案

在现实生活中一切都更容易。对于每个组件,您需要回答以下问题。

What data the component will receive? Does it emit any event?

That's the props of the component.

所以无论你的组件之间的关系如何......只要回答这些问题就可以了。

示例:

我有一个 TodoList,其中包含 TodoItem 元素列表。 (家长)

我有一个显示 TodoItem 内容的 TodoItem。 ( child )

我有一个显示复选框的Checkbox。 (孙子)

CheckBox 接收一个 bool 值,表示 isSelected 并发出 onChange 事件。这就是我所知道的全部。

TodoItem 接收 Todo 并发出 onChange。这就是我所关心的。

当你把所有东西放在一起时,TodoList有一个todos,并将todos[i]传递给它的 child 和todos[ i].isSelected 给它的孙子,但这是你不需要关心的。您关心的只是:

What data the component will receive? Does it emit any event?

在组件级别。

关于javascript - react : How to pass values from grandchild through child to parent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870127/

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