2017-06-20 100 views
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()

相關問題