【问题标题】:How to update styles on child component onPress in react native如何在本机反应中更新子组件onPress的样式
【发布时间】:2019-05-14 13:19:29
【问题描述】:

我为 react native 创建了一个组件来显示选项列表(单选按钮)。

它基本上是一个带有视图和文本的 TouchableOpacity。显示单选按钮圆圈和标签文本的视图。我已经向 TouchableOpactiy 添加了一个 onPress 处理程序。我想更改 TouchabelOpacity 内 View 的样式...

我认为在状态更改时组件会更新...

我错过了什么/做错了什么?

这是我的代码的一部分(完整代码:https://codesandbox.io/s/7knoyx5v9j

class RadioButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { value: props.selected ? props.selected : null };
    this.handleRadioButtonChange = this.handleRadioButtonChange.bind(this);
  }
  handleRadioButtonChange = event => {
    this.setState({ value: event.target.value });
  };
  render() {
    const { disabled, name, options } = this.props;
    const { value } = this.state;
    const radioOptions = options.map(radio => (
      <TouchableOpacity
        key={radio[1].toString()}
        id={value}
        name={name}
        value={radio[1]}
        disabled={disabled}
        onPress={this.handleRadioButtonChange}
      >
        <View style={value === radio[1] ? styleActive : styleInactive} />
        <Text>{radio[0]}</Text>
      </TouchableOpacity>
    ));
    return radioOptions;
  }
}

【问题讨论】:

  • 不要将一组选项传递给单选按钮类,然后将它们映射到类中,而是尝试使单选按钮成为单个组件并映射选项数组以创建单选按钮。

标签: javascript reactjs react-native


【解决方案1】:

是的,你的价值是不确定的.. 使用这个修改后的代码,现在它可以按你的意愿工作了..

    class RadioButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { value: props.selected ? props.selected : null };
  }
  handleRadioButtonChange = event => {
    this.setState({ value: event });
  };
  render() {
    const { disabled, name, options } = this.props;
    const { value } = this.state;
    const radioOptions = options.map(radio => (
      <TouchableOpacity
        key={radio[1].toString()}
        id={value}
        name={name}
        value={radio[1]}
        disabled={disabled}
        onPress={() => this.handleRadioButtonChange(radio[1])}
      >
        <View style={value === radio[1] ? styleActive : styleInactive} />
        <Text>{radio[0]}</Text>
      </TouchableOpacity>
    ));
    return radioOptions;
  }
}

详细说明为什么我使用箭头而不是绑定.. 试试这两个代码,它会给你更多有趣的事实

【讨论】:

    【解决方案2】:

    event.target.valueundefined,因此条件总是呈现非活动样式。

    handleRadioButtonChange = value => event => {
        this.setState({ value });
    };
    
    <TouchableOpacity
       ...
       onPress={this.handleRadioButtonChange(radio[1])}
    >
    

    查看更多关于活动here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2020-08-02
      • 2022-09-27
      相关资源
      最近更新 更多