【问题标题】:undefined is not an object (evaluating '_this2.onRadioPressed')undefined 不是对象(评估 '_this2.onRadioPressed')
【发布时间】:2017-05-30 03:45:09
【问题描述】:

我正在使用我的组件构建单选按钮,并且按钮构建良好,但 onPress 无法正常工作。单击单选按钮时,标题中出现错误。我怀疑,基于错误,“这”不是我想的那样。任何帮助表示赞赏。以下是相关代码:

let radio_props = [
        {label: 'forward', value: 0 },
        {label: 'back', value: 1 }
    ];

<RadioBtn
    radioGroupLabel={'Main Label'}
    radioLabels={radio_props}
    style={styles.radioElement}>
</RadioBtn>

然后在我的 RadioBtn.js 文件中...

onRadioPressed = (val) => { console.log('VAL:', val); this.setState({selectedValue:val}); };

renderRadios(obj, i) {
    console.log('OBJ:', obj);
  return (
      <View style={styles.firstRadioContainer}>
          <TouchableOpacity
              onPress={(value, index) => {
                  this.onRadioPressed(obj.value)
              }}
              underlayColor='#f1c40f'>
              <Text value={obj.value} style={styles.radio}>{obj.label}</Text>
          </TouchableOpacity>
      </View>
  )
};

render() {

    let renderedRadios = this.props.radioLabels.map(this.renderRadios);

    return (
        <View>
            <View style={styles.radioLabelContainer}>
                <Text style={styles.radioLabel}>{this.props.radioGroupLabel}</Text>
            </View>
            <View style={styles.radioGrp}>
                {renderedRadios}
            </View>
        </View>
    );
};

【问题讨论】:

    标签: react-native


    【解决方案1】:

    你是对的,renderRadios 方法中的this 不再指向 RadioBtn 类,因为你在数组的 map 方法中调用的方式。

    尝试使用arrow function expression更改为以下内容:

    let renderedRadios = this.props.radioLabels.map((o, i) => this.renderRadios(o, i));
    

    【讨论】:

    • 完美。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2015-07-16
    相关资源
    最近更新 更多