引用值在React Native中始终未定义

时间:2019-12-18 15:58:11

标签: javascript react-native undefined ref

我不明白为什么我的裁判的值总是不确定的。我知道这类问题已经发布,但没有帮助。

这是我的代码:

class CallsHandler extends React.Component {
    constructor(props) {
        super(props);
        this.handleRegistration = this.handleRegistration.bind(this);
        this.usernameInput = React.createRef();
    }
    handleRegistration() {
        console.log(this.usernameInput.current.value);
    }
    render () {
        return (
            <View>
                <Text>Username</Text>
                <TextInput ref={this.usernameInput}></TextInput>
                <Button title="REGISTER" onPress={this.handleRegistration}/>
            </View>
        )
    }
}

3 个答案:

答案 0 :(得分:0)

您必须将方法绑定到组件上下文

onPress = {this.handleRegistration.bind(this)}

答案 1 :(得分:0)

尝试用<TextInput> HTML标记替换<input>组件,看看是否仍然存在相同的问题。此外,您是否考虑过将onPress更改为onClick?这些是我实施中的唯一区别,我没有问题。

答案 2 :(得分:0)

尝试一下:

    <TextInput ref={input => (this.nameInput = input)}></TextInput>

也请删除此行this.usernameInput = React.createRef();