【问题标题】:React Native - Update Parent State in Child with Dynamic KeyReact Native - 使用动态键更新子级中的父级状态
【发布时间】:2018-11-21 17:31:00
【问题描述】:

我对 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 个函数,每个函数都更新期望状态。然而,虽然这适用于我的基本应用程序,但我正在寻找一种对未来项目更具可扩展性的方法。谢谢!

【问题讨论】:

  • 我将这些片段按原样放入沙箱中,它似乎可以工作,也许我误解了你的问题? codesandbox.io/s/95v45pj7w
  • 你好 SpeedOfRound!谢谢,它现在正在工作。在将您的代码与我的代码进行比较时,我可能已经解决了一个我不知道的问题。我很珍惜时间

标签: javascript react-native


【解决方案1】:

在父级中 而不是在子键的 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

【讨论】:

  • 您好 md.warish Ansari 感谢您的回复。不幸的是,我试图避免对子组件中的密钥进行硬编码,因为我重复使用了 6 次。我应该更清楚我的变量名。我想从父组件传递密钥,所以每次使用子组件时,我都可以自定义它更新父组件的哪个状态。
  • @holdenmaudlin 我建议将您的“幻数”放入常量文件并根据需要导入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多