onChange不适用于手机吗? -React Native

时间:2020-07-15 16:00:17

标签: javascript react-native

现在我正在尝试创建一个“登录页面”,并且我一直在使用React Native来做。它在网络浏览器上可以正常工作,但是当我在手机上尝试使用时,onChange似乎并没有更改密码和用户名的状态。

import React from 'react';
import { TextInput, View, TouchableOpacity, Text } from 'react-native';


class LogIn extends React.Component {
    
    constructor(props){
      super(props);
      this.state={
        username: 'John Doe',
        password: 'abc123'
      }
    }
    loginChangeHandler = (event) =>{
      this.setState({[event.target.name]: event.target.value});
    }
  
    loginButtonHandler = () =>{
      
      alert('username: '+this.state.username+ ' Password: '+this.state.password)
    }
    render() {
        return (
         
          <View  style = {{alignItems: 'center'}}>
          
          <TextInput name = 'username' onChange  = {this.loginChangeHandler}
            placeholder = 'username'
            style={{ width: 200, height: 55, borderColor: 'gray', borderWidth: 1 }}
          />
          <Text>{'\n'}</Text>
          <TextInput name = 'password' onChange  = {this.loginChangeHandler} secureTextEntry={true}
            placeholder = 'password'
            style={{ width: 200, height: 55, borderColor: 'gray', borderWidth: 1 }}
          />
          <Text>{'\n'}</Text>
          <TouchableOpacity onPress = {this.loginButtonHandler} style = {{height: 45, width: 200, justifyContent: 'center',  alignItems: "center", backgroundColor: 'green'}}>
          <Text style = {{fontSize: 16, color: 'white'}}>LOG IN</Text>
          </TouchableOpacity>
          
          
          </View>
          
        );
      }
}




export default LogIn;

1 个答案:

答案 0 :(得分:0)

要在函数内部使用this,必须将函数与this对象绑定。另一件事是name组件没有直接的TextInput道具,并且event.target没有返回您期望的东西。用{ nativeEvent: { eventCount, target, text} }调用onChange,然后建议您使用onChangeText回调。仅使用您键入的值调用此回调。

以这种方式更改代码。

render() {
        return (
         
          <View  style = {{alignItems: 'center'}}>
          
          <TextInput name = 'username' onChangeText= {(value) => this.setState({ username : value })}
            placeholder = 'username'
            style={{ width: 200, height: 55, borderColor: 'gray', borderWidth: 1 }}
          />
          <Text>{'\n'}</Text>
          <TextInput name = 'password' onChangeText={(value) => this.setState({ password : value })} secureTextEntry={true}
            placeholder = 'password'
            style={{ width: 200, height: 55, borderColor: 'gray', borderWidth: 1 }}
          />
          <Text>{'\n'}</Text>
          <TouchableOpacity onPress = {this.loginButtonHandler.bind(this)} style = {{height: 45, width: 200, justifyContent: 'center',  alignItems: "center", backgroundColor: 'green'}}>
          <Text style = {{fontSize: 16, color: 'white'}}>LOG IN</Text>
          </TouchableOpacity>
          
          
          </View>
          
        );
      }