反应:如何将值从孙子通过孩子传递给父母?

反应:如何将值从孙子通过孩子传递给父母?

问题描述:

我有一个父母,孩子和孙子组件。我有不同的输入字段,并希望将值从孙子到孩子传递给父母,最终我将值设置为状态。我没有包括我所有的代码,但是这样做是必要的,因为我的代码中有其他的东西,我没有在这篇文章中将它包括进来,因为它是不相关的。林不知道如何做到这一点,并试图实现我在网上找到的,但是,它不工作。有任何想法吗?谢谢!!反应:如何将值从孙子通过孩子传递给父母?

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> 
    ) 
} 
+0

这打破了很大一部分组件隔离。组成部分不应该与父母沟通,他们甚至不应该“意识到”父母成分。父母*可以控制孩子*,但不能反过来。 – Li357

在现实生活中一切都比较容易。对于每个组件你回答以下问题。

该组件将收到什么数据? 它发出任何事件吗?

这就是组件的props

所以不管你的组件之间的关系如何......只要回答这些问题,你就会很好。

实施例:

我有一个TodoList包含TodoItem元素的列表。 (Parent)

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

我有一个Checkbox显示一个复选框。 (GrandChild)

a CheckBox收到布尔语isSelected并发出和事件onChange。这就是我所知道的。

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

当你把一切融合在一起,TodoListtodos,并通过todos[i]到其子和todos[i].isSelected其孙子,但毕竟是你不需要的东西关心。所有你关心的是:

该组件将收到什么数据?它发出任何事件吗?

在组件级别。