简体   繁体   English

如何像道具一样传递 state 值

[英]How pass state value like a props

i'd radio button component:我要单选按钮组件:

state = {
    radioValue: null,
  }



  render() {
    const { options,onPress } = this.props;
    const { radioValue } = this.state;

    return (
      <View style={{flexDirection: 'row'}}>
        {options.map(item => {
          return (
            <View key={item.key} style={styles.buttonContainer}>
              <TouchableOpacity
                style={styles.circle}
                onPress={() => {
                  this.setState({
                    radioValue: item.key,
                  });
                }}
              >
                {radioValue === item.key && <View style={styles.checkedCircle} />}
              </TouchableOpacity>
              <Text>{item.text}</Text>
            </View>
          );
        })}
      </View>
    );

then i use this component in an another like this:然后我在另一个这样的组件中使用这个组件:

 <RadioButton options={options} />  

How can i use the value of my state in the second component??如何在第二个组件中使用我的 state 的值? Thx !!谢谢 !!

The best way would be to move the state from RadioButton to the outer component:最好的方法是将 state 从RadioButton移动到外部组件:

// RadioButton Component
  render() {
    const { options, onPress, value } = this.props;

    return (
      <View style={{flexDirection: 'row'}}>
        {options.map(item => {
          return (
            <View key={item.key} style={styles.buttonContainer}>
              <TouchableOpacity
                style={styles.circle}
                onPress={() => onPress(item.key)} // onPress comes from parent
              >
                {value === item.key && <View style={styles.checkedCircle} />}
              </TouchableOpacity>
              <Text>{item.text}</Text>
            </View>
          );
        })}
      </View>
    );
// Parent component
  state = {
    radioValue: null,
  }

  onPress = (value) => {
    this.setState({
      radioValue: value,
    });
  }

  render() {
    // ...
    <RadioButton
      options={options}
      onPresss={this.onPress}
      value={radioValue}
    />  
    // ...
  }

If you can't do that, another approach would be using render props .如果你不能这样做,另一种方法是使用render props This would let you keep the state in the child, and pass it to the parent.这将让您将 state 保留在子级中,并将其传递给父级。 Not recommended, though, as it is more confusing.但不推荐,因为它更令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM