【问题标题】:React Native - Modify a prop within the same componentReact Native - 在同一个组件中修改一个 prop
【发布时间】:2017-06-20 04:07:08
【问题描述】:

我有简单的问题:

  1. 是否可以在 React Native 组件(不是来自父组件)中修改 prop(不是 state)?

  2. 按照 [1],如果我想在同一个组件中修改一个 prop,我该如何实现(或者如果 [1] 中的答案是否定的,解决方法)?

  3. 如果我有以下情况:

//父母

render(){
  return <View><ChildComponent propA={this.state.propA} /></View>
}

triggerChangeInParent(val) {
  this.setState({
    propA: val
  });
}

//子(子组件)

render() {
  return <View><Text>{this.props.propA}</Text></View>
}

triggerChangeInChild(val) {
  //To set props.propA here
}

父组件和子组件都可以修改“propA”。谁触发了最新的将优先修改“propA”(例如,如果“triggerChangeInChild”在“triggerChangeInParent”之后触发,则“triggerChangeInChild”中的“val”将用于“propA”。

我的问题是,我们如何实现这一点(有什么可能的解决方案/替代方案来解决这个问题)?最佳实践/模式是什么?

谢谢!

【问题讨论】:

  • 道具是只读的。你为什么要改变道具呢?如果是这种情况,可能需要进行一些重构。
  • 重构可能是终极之举。现在更改成本很高(由于遗留问题,我们修复的时间非常有限)。只是寻求公众的建议,看看是否有可能通过变通方法/解决方案。

标签: javascript design-patterns mobile react-native ecmascript-6


【解决方案1】:
  1. State 是可变的,props 是不可变的,所以你不能修改组件内的 props。请在当前组件之外进行。如果您使用的是 redux,则可以在 reducer 中进行。

  2. 你应该只在parent上修改propA,请在parent中写一个方法,然后通过prop传递给child。所以你可以从 child 调用方法,意味着你在 child 内部进行更改。

    父母

    contractor(props){
    
       super(props)
       this.modifyPropsOnParent =  this.modifyPropsOnParent.bind(this)
    }
    modifyPropsOnParent(){
    
       // do your change here
    }
    
    render() {
       return <Child modifyPropsOnParent={this.modifyPropsOnParent} otherProp={yourProps} />
    }
    

child 可以通过 this.props 调用父方法。 modifyPropsOnParent()

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 2017-04-30
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 2018-10-20
    • 2019-10-23
    • 2023-03-04
    • 2021-03-18
    相关资源
    最近更新 更多