簡體   English   中英

使用react-router時,如何從子組件中設置父組件的狀態?

[英]How can I set the state of my parent component from the child component when using react-router?

我正在一個React項目上,向用戶提示一系列問題,這些問題的答案將被合並為要保存的對象。

父組件包含多個子組件。

例如 -

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

父級的初始狀態為空值ex。 (this.state = {value1:“”,value2:“”})

使用{this.props.children}時,如何將數據從子級傳遞到父級(道具從父級傳遞到子級)?

與其使用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>

為什么用這種方式呢? 好了,如您所見,現在您可以將prop傳遞給渲染的子對象(在此示例中為someProp )。 現在您可以將道具傳遞給孩子了, 使用回調從孩子那里修改父狀態變得很簡單

有關render道具的更多信息,請參見此處。

為了使父級從子級獲取數據,您需要將回調函數作為屬性傳遞給該子級。

callbackFunction(data) {
    // do something
}

<ChildComponent parentCallback={this.callbackFunction} />

然后,您可以在子組件中使用prop將數據發送回其父組件,然后父組件將使用回調函數對其執行某些操作。

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

查看以下文章以了解更多詳細信息: https : //medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM