簡體   English   中英

React Native-使用動態密鑰更新子級中的父狀態

[英]React Native - Update Parent State in Child with Dynamic Key

我對Javascript和React Native都非常陌生,我正在嘗試通過使用回調鍵(使用動態鍵)來更新父狀態,以避免編寫多個函數。

在父組件中,我將此函數傳遞給子對象,以根據用戶文本輸入來更新父狀態。 這段代碼可以達到預期的效果

在家長中:

_setAge = (value) => {
this.setState({age: value})}

<ChildComponent name = 'Update Age' _setAge = { this._setAge.bind(this) } />

在兒童中:

//Other child code
<TextInput onChangeText = { (input) => {this.props._setAge(input)} }
//Etc.

但是,我正在尋找一種將所需的狀態鍵從父級傳遞給子級以動態更新狀態的方法。 我嘗試了以下方法:

在家長中:

const ageKey = 'age'

_setAge = (value, stateKey) => {
this.setState({ [stateKey]: value })}

<ChildComponent name = 'Update Age' _setAge = { this._setAge.bind(this) } stateKey = ageKey } />

在兒童中:

//Other child code
<TextInput onChangeText = { (input) => this.props._setAge(input, this.props.stateKey)
//Etc.

但是,這不起作用。 我目前的工作是為我的6個子組件編寫6個函數,每個函數都更新期望狀態。 但是,盡管這對於我的基本應用程序是可行的,但我正在尋找一種對將來的項目更具可伸縮性的方法。 謝謝!

在父級中,而不是在子項上的props中傳遞stateKey,而直接在子項中的onChageText方法中傳遞狀態鍵。 代碼看起來像這樣->>>>

_setAge = (value, stateKey) => {  
this.setState({ [stateKey]: value })}

<ChildComponent name = 'Update Age' _setAge = {this._setAge} /> // providing no statekey here

在孩子里面

<TextInput onChangeText = { (input) => this.props._setAge(input, 'age') } 
   // here i know statekey for each child so i directly pass the key from child so i dont have to pass it as a props and then access it

暫無
暫無

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

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