2017-07-26 172 views
0

我在一個陣營項目中,用戶將被提示一系列問題的工作,這些問題的答案將被合併爲對象進行保存。如何在使用react-router時從子組件設置父組件的狀態?

父組件包含幾個孩子。

爲example--

<Route path="Parent" component={Parent}> 
 
    <Route path="Child1" component={Child1} /> 
 
    <Route path="Child2" component={Child2} /> 
 
    <Route path="Child3" component={Child3} /> 
 
    <IndexRoute component={Child1} /> 
 
</Route>

父將具有空值 前的初始狀態。 (this.state = {value1:「」,value2:「」})

使用{this.props.children時,如何將數據從孩子傳遞給父母(以及從父母到孩子的道具) }?

回答

3

除了使用component道具使你的孩子的路線,使用render道具。這允許你有一個函數返回你想渲染的組件,而不是簡單地接受這個類本身。它看起來像這樣:

<Route path="Parent" component={Parent}> 
    <Route path="Child1" render={() => {<Child1 someProp={foo} />}} /> 
    <Route path="Child2" render={() => {<Child2 someProp={bar} />}} /> 
    <Route path="Child3" render={() => {<Child3 someProp={baz} />}} /> 
    <IndexRoute component={Child1} /> 
</Route> 

爲什麼要這樣呢?那麼,正如你所看到的,現在你可以將道具傳遞給渲染的孩子(在這個例子中,someProp)。而現在,你可以通過道具的孩子,這是微不足道的use callbacks to modify parent state from the children.

More info on the render prop here.

+0

太好了。請考慮不要使用'state'並將實現移到''''''''''''''''''''''如' – Hitmands

+0

對於反應路由器v4,這是一個首選的方式,只要確保使用渲染而不是組件來避免額外的安裝和重新渲染。 –

+0

正是我在找的,謝謝! –

1

爲了讓父母擺脫其子回數據,你需要傳遞一個回調函數作爲一個屬性給孩子。

callbackFunction(data) { 
    // do something 
} 

<ChildComponent parentCallback={this.callbackFunction} /> 

然後你可以使用道具的子組件內將數據發送回給其父,然後將使用回調函數來用它做什麼。

const x = ["a", "b", "c", "d"]; 
this.props.parentCallback(x); 

檢查下面的文章瞭解詳情:https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

另一種選擇是使用像Redux的狀態容器。在這種情況下,您的子組件會將值分派給某個狀態,並且此狀態正由其父級監聽,並在狀態更改時重新呈現。這是更復雜場景的解決方案

相關問題