Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React Native-修改同一组件中的道具_Javascript_Design Patterns_Mobile_React Native_Ecmascript 6 - Fatal编程技术网

Javascript React Native-修改同一组件中的道具

Javascript React Native-修改同一组件中的道具,javascript,design-patterns,mobile,react-native,ecmascript-6,Javascript,Design Patterns,Mobile,React Native,Ecmascript 6,我有一些简单的问题: 是否可以修改React本机组件(非父组件)内的属性(非状态) 在[1]之后,如果我想修改同一组件中的道具,我该如何实现这一点(或者如果[1]中的答案为“否”时的变通方法) 如果我有以下资料: //母公司 render(){ return <View><ChildComponent propA={this.state.propA} /></View> } triggerChangeInParent(val) { this.setS

我有一些简单的问题:

  • 是否可以修改React本机组件(非父组件)内的属性(非状态)

  • 在[1]之后,如果我想修改同一组件中的道具,我该如何实现这一点(或者如果[1]中的答案为“否”时的变通方法)

  • 如果我有以下资料:

  • //母公司

    render(){
      return <View><ChildComponent propA={this.state.propA} /></View>
    }
    
    triggerChangeInParent(val) {
      this.setState({
        propA: val
      });
    }
    
    render(){
    返回
    }
    触发器更改属性(val){
    这是我的国家({
    普罗帕:瓦尔
    });
    }
    
    //子(子组件)

    render(){
    返回{this.props.propA}
    }
    triggerChangeInChild(val){
    //在这里设置props.propA
    }
    
    父组件和子组件都可以修改“propA”。无论谁触发最新版本,其值将优先用于修改“propA”(例如,如果在“triggerChangeInParent”之后触发“triggerChangeInChild”,则“triggerChangeInChild”中的“val”将用于“propA”

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

    谢谢

  • 状态是可变的,而道具是不可变的,因此您不能在组件内修改道具。请在当前组件外进行修改。如果您使用的是redux,则可以在reducer中进行修改

  • 您应该仅在父级上修改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.modifyPropsOnParent=this.modifyPropsOnParent.bind(this)
    }
    modifyPropsOnParent(){
    //找你钱吗
    }
    render(){
    返回
    }
    

  • Child可以通过此方法调用父方法。props.modifyPropsOnParent()

    道具是只读的。你为什么还要尝试变异道具?如果是这样的话,可能需要进行一些重构。重构可能是最终的举措。目前的更改成本相当高(由于遗留的东西,我们修复的时间非常有限)。只是向公众寻求建议,看看这是否有可能通过变通办法/解决方案实现。
    contractor(props){
    
       super(props)
       this.modifyPropsOnParent =  this.modifyPropsOnParent.bind(this)
    }
    modifyPropsOnParent(){
    
       // do your change here
    }
    
    render() {
       return <Child modifyPropsOnParent={this.modifyPropsOnParent} otherProp={yourProps} />
    }