0

内修改的道具我有简单的问题:阵营原住民 - 同一组件

  1. 是否有可能一个阵营本地组件(不是从父组件)中修改的道具(不是国家)?

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

  3. 如果我有以下几点:

//父

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

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

//子(ChildComponent)

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

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

父母和子女有组件允许修改“propA”。无论谁触发最新的操作,其修改“propA”的优先级值(例如,如果triggerChangeInParent后触发“triggerChangeInChild”,那么“triggerChangeInChild”中的“val”将用于“propA”。

我的问题是,我们如何做到这一点(有什么可能的解决方案/替代品来解决这个问题)?什么是最好的做法/模式?

谢谢!

+1

道具是只读的。你为什么试图改变道具呢?如果是这样的话,可能有一些重构要做。 – Li357

+0

重构可能是最终的举措。现在变化是相当昂贵的(由于传统的东西,我们有相当有限的修复时间)。只是寻求公众的意见,看看这是可行的解决方案/解决方案。 – oatcrunch

回答

0
  1. 国家是可变的,道具是不变的,所以你无法修改组件中的道具,请在当前组件外部进行修改,如果您使用的是redux,则可以使用redux CER。

  2. 您应该只修改父母的propA,请在父母中写一个方法,然后通过prop将它传递给孩子。所以你可以从孩子那里调用这个方法,这意味着你在孩子内部进行了修改。

    家长

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

儿童可以调用this.props父类的方法。 modifyPropsOnParent()

相关问题