React Native - 按下按钮时更新状态

问题描述:

我目前有两个按钮(No,Yes)(从native-base包导入的组件),按下时应分别用0或1更新状态,并在true或如果此字段已填充,则为false(默认情况下,两者都不会被按下,因此设置为false)。React Native - 按下按钮时更新状态

我有一个handleOnClick()函数绑定到“否”按钮与调试器来测试,如果我真的打它,但一旦进入此功能,我不知道如何抓住关联组件的任何信息(即Text组件中的“No”文本),所以我可以执行逻辑来检查是否按下“否”或“是”。

如果这是在纯React中完成的,我知道我可以访问某些数据属性,我添加到DOM元素或遍历DOM,但我不知道如何在React Native中执行此操作,或者如果我可以将自定义道具添加到可以访问的内置组件中。

class Toggle extends Component { 
    constructor() { 
    super() 

    this.state = { 
     selectedOption: '', 
     isFilled: false 
    } 

    this.checkField = this.checkField.bind(this) 
    this.handleOnClick = this.handleOnClick.bind(this) 
    } 

    checkField() { 
    console.log(this) 
    // debugger 
    } 

    handleOnClick(ev) { 
    debugger 
    console.log("I was pressed") 
    } 

    render() { 
    const options = this.props.inputInfo.options //=> [0,1] 
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"] 

    return (
     <View style={{flexDirection: 'row'}}> 
     <View style={styles.row} > 
      <Button light full onPress={this.handleOnClick}><Text>No</Text></Button> 
     </View> 
     <View style={styles.row} > 
      <Button success full><Text>Yes</Text></Button> 
     </View> 
     </View> 
    ) 
    } 
} 
+0

我会记录'ev.target.value'来看看你给了什么。否则,您可能需要深入了解该事件以查找子文本的值文本元素 – Alastair

如果要将信息传递到函数中,可以在调用它时传递它。你的情况,你可以从箭头函数调用你的函数,像这样:

 <View style={{flexDirection: 'row'}}> 
     <View style={styles.row} > 
      <Button light full onPress={() => this.handleOnClick('No')}> 
      <Text>No</Text> 
      </Button> 
     </View> 
     <View style={styles.row} > 
      <Button success full><Text>Yes</Text></Button> 
     </View> 
     </View> 

而在你的功能

handleOnClick(text) { 
    debugger 
    console.log(`${text} pressed`) 
    } 
+0

太棒了!这是我需要的! – jamesvphan

你试过:

render() { 
    const options = this.props.inputInfo.options //=> [0,1] 
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"] 

return (
    <View style={{flexDirection: 'row'}}> 
    <View style={styles.row} > 
     <Button light full onPress={() => this.handleOnClick('No')}><Text>No</Text></Button> 
    </View> 
    <View style={styles.row} > 
     <Button success full onPress={() => this.handleOnClick('Yes')}><Text>Yes</Text></Button> 
    </View> 
    </View> 
) 

}

handleOnClick(word) { 
    this.setState({ selectedOption: word, isFilled: true }) 
    }