this.refs返回未定义的值

时间:2018-12-31 13:06:45

标签: android react-native

我是React-native还是android的新手,单击按钮后,当我尝试访问TextInput中引用的值时,得到了未定义的响应

在查看以前的解决方案时,我尝试绑定登录按钮,但问题仍未解决

function login(event)
{
var email = this.refs.email;
var password = this.refs.password;

console.log(email + ": " + password); // gives undefined: undefined

}

export default class App extends Component {
render() {
    return (
    <View style={styles.container}>
        <Image source={require('./logo.png')} />
        <Text style={styles.welcome}>Login</Text>

        <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 300}}
        placeholder={'E-mail'}
        ref = {this.email}
        onChangeText={(text) => this.setState({text})}
        />
        <Text>{"\n"}</Text>
        <TextInput secureTextEntry={true}
        style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 300}}
        placeholder={'Password'}
        ref = {this.password}
        onChangeText={(text) => this.setState({text})}
        />
        <Text>{"\n"}</Text>
        <Button 
        title="Log In" 
        onPress={login.bind(this)}
        />

    </View>
    );
}
}

1 个答案:

答案 0 :(得分:2)

不建议使用this.refs

使用refs作为函数。例如:

export default class App extends Component {
    let viewRef = null;

    render() {
        return (
            <View ref={ref => (this.viewRef = ref)}>
                <Button 
                    title="Log In" 
                    onPress={() => console.log(this.viewRef)}
                />
            </View>
        )
    }
}
相关问题