2017-12-18 157 views
0

我有一個父母,孩子和孫子組件。我有不同的輸入字段,並希望將值從孫子到孩子傳遞給父母,最終我將值設置爲狀態。我沒有包括我所有的代碼,但是這樣做是必要的,因爲我的代碼中有其他的東西,我沒有在這篇文章中將它包括進來,因爲它是不相關的。林不知道如何做到這一點,並試圖實現我在網上找到的,但是,它不工作。有任何想法嗎?謝謝!!反應:如何將值從孫子通過孩子傳遞給父母?

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

回答

0

在現實生活中一切都比較容易。對於每個組件你回答以下問題。

該組件將收到什麼數據? 它發出任何事件嗎?

這就是組件的props

所以不管你的組件之間的關係如何......只要回答這些問題,你就會很好。

實施例:

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

我有一個顯示TodoItem內容的TodoItem。 (Child)

我有一個Checkbox顯示一個複選框。 (GrandChild)

a CheckBox收到布爾語isSelected併發出和事件onChange。這就是我所知道的。

a TodoItem收到Todo併發出onChange。這就是我所關心的。

當你把一切融合在一起,TodoListtodos,並通過todos[i]到其子和todos[i].isSelected其孫子,但畢竟是你不需要的東西關心。所有你關心的是:

該組件將收到什麼數據?它發出任何事件嗎?

在組件級別。

相關問題