如何从本机反应中的文本输入访问值?

How can I access the value from the text input in react native?

我有以下代码,我想获取已输入到文本框中的值的警报,如何访问该值? (在 alertFunction 中):

    alertFunction(text){
        Alert.alert(this.state.text);

    }    

validate(text, type) {
    num = /^[0-9]+$/
    if (type == 'telephone') {
        if (num.test(text)) {
            this.setState({
                telephoneValidate: true,
                buttonInvalid: false,
            })
        } else {
            this.setState({
                telephoneValidate: false,
                buttonInvalid: true,
            })
        }
    }
}




<TextInput
                style={[!this.state.telephoneValidate ? { borderWidth: 3, borderColor: 'red' } : null]}
                keyboardType='numeric'
                onChangeText={(text) => this.validate(text, 'telephone')}
                value={this.state.myNumber}
                maxLength={10}  //setting limit of input
            />

            <TouchableOpacity style={[styles.ButtonStyle, { backgroundColor: this.state.buttonInvalid ? '#607D8B' : '#009688' }]}
                activeOpacity={.5}
                disabled={this.state.buttonInvalid}
                onPress={this.alertFunction} 
      >

                <Text style={styles.TextStyle}>Submit</Text>

            </TouchableOpacity>

谢谢

您对状态对象有点困惑。对于文本输入组件,您将值绑定到 this.state.myNumber,但如果正确验证,您永远不会尝试调整该值。但是您正试图引用 this.state.text 来获取警报。你需要做几件事。

首先调整您的验证以在有效时更新您关心的状态对象。

validate(text, type){ 
   ..is valid
   this.setState({ 
      ..other items,
      myNumber: text
   });

这将正确更新您的状态,然后当您想要提醒时,您可以访问那个 属性。

alertFunction(text){
    Alert.alert(this.state.myNumber);
    }