从子组件获取父元素状态

时间:2018-02-04 14:07:44

标签: reactjs react-native jsx

我有一个状态发生变化的组件,我想从父组件中获取“性别”的值。我怎么能这样做?

class CardSegment extends Component {

  constructor(props) {
    super(props);
    this.state = { gender: 'male', val: true };
  }

  render() {
    return (
      <StyleProvider style={getTheme(commonColor)}>
        <Segment style={styles.SegmentStyle}>
          <Button
            active={this.state.val}
            onPress={() => this.setState({ gender: 'male', val: true })}
            style={styles.SegmentBtnStyle}
          >
            <Text style={styles.textStyle}>Male</Text>
          </Button>
          <Button
            active={!this.state.val}
            onPress={() => this.setState({ gender: 'female', val: false })}
            style={styles.SegmentBtnStyle}
          >
            <Text style={styles.textStyle}>Female</Text>
          </Button>
        </Segment>
      </StyleProvider>
    );
  }

}

1 个答案:

答案 0 :(得分:0)

假设您有父组件执行某些逻辑并将gender作为道具传递..(无状态组件)

const ParentComponent= props => {
  const gender= 'your parent component should handle the "gender" logic here'

  return <CardSegment gender={gender} />;
};

在CardSegment(子组件!!?!)中,仅使用componentWillReceiveProps生命周期方法同步更新状态。

class CardSegment extends Component {

constructor(props) {
  super(props);
  this.state = { gender: '', val: true }; 
}
componentWillReceiveProps(props){
  this.setState({gender: this.props.gender });
}
  render() {
    return (
    <StyleProvider style={getTheme(commonColor)}>
      <Segment style={styles.SegmentStyle}>
        <Button
          active={this.state.val}
          onPress={() => this.setState({ gender: 'male', val: true })}
          style={styles.SegmentBtnStyle}
        >
          <Text style={styles.textStyle}>Male</Text>
        </Button>
        <Button
          active={!this.state.val}
          onPress={() => this.setState({ gender: 'female', val: false })}
          style={styles.SegmentBtnStyle}
        >
          <Text style={styles.textStyle}>Female</Text>
        </Button>
      </Segment>
    </StyleProvider>
    );
  }
}