首页 > 解决方案 > React Native 中的 Ref 值始终未定义

问题描述

我不明白为什么我的 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>
        )
    }
}

标签: javascriptreact-nativeundefinedref

解决方案


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

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


推荐阅读