2016-03-04 89 views
2
component A 

render(){ 
    <View> 
     {this.renderB()} 
     {this.renderC()} 
    </View> 
} 

component B 

super(props){ 
    this.state={text: (this.props.text) ? this.props.text : '' } 
} 
render(){ 
} 

component C 

super(props){ 
} 
render(){ 
    <View> 
     <TouchableHighlight onPress={ 
    ...here I want to modify text state of component B 
    }></TouchableHighlight> 
    </View> 
} 

是否可以像這樣修改同級的狀態?還是應該將text屬性移到組件A?操縱同級組件的狀態

回答

3

當您需要在組件之間共享狀態時,將該狀態移至其共同的父級並通過道具向下推動它們。

以下是我所得到的要點。顯然,你需要傳遞實際值。

class ComponentA extends React.Component{ 
    constructor(props){ 
    super(props); 

    this.state = { 
     text: '', 
    } 
    } 

    render(){ 
    return (
     <View> 
     <ComponentB text={this.state.text}> 
     <ComponentC onPress={(value) => this.setState({text: value})}> 
     </View> 
    ) 
    } 
} 

class ComponentB extends React.Component{ 
    render(){ 
    return(
     <Text>{this.props.text}</Text> 
    ) 
    } 
} 

class ComponentC extends React.Component{ 
    render(){ 
    return(
     <View> 
     <TouchableHighlight onPress={this.props.onPress} /> 
     </View> 
    ) 
    } 
}