2017-01-15 82 views
0

我建立單選按鈕使用我的組件和按鈕內置好,但onPress不工作。單擊單選按鈕時,我會在標題中看到錯誤。我懷疑,基於這個錯誤,'這'不是我認爲的。任何幫助表示讚賞。下面是相關的代碼:未定義不是一個對象(評估'_this2.onRadioPressed')

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> 
    ); 
}; 

回答

0

你是對的,this在renderRadios方法不再指向RadioBtn類的,因爲你在數組的map方法調用的方式。

嘗試使用arrow function expression更改爲以下幾點:

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

完美。非常感謝你! – miarde

+0

不客氣。 –

相關問題