【发布时间】: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!谢谢,它现在正在工作。在将您的代码与我的代码进行比较时,我可能已经解决了一个我不知道的问题。我很珍惜时间