当从本机上的TextInput获取值时,未定义错误不是对象

时间:2019-08-24 03:36:59

标签: react-native react-native-android

class LoginComponent extends Component {
   constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
  }
  onLogin() {
    const { email, password } = this.state;
    alert(email);
  }
  renderInput = (
    placeholder: string,
    type: string,
    name: string,
    value: string
  ): Object => (
      <Input
        placeholder={placeholder}
        type={type}
        name={name}
        value={this.state[name] || value}
        onChangeText={({target}) => this.setState({[name]: target.value})}
      />
    ); 
   render() {
      return (
      ...
      {this.renderInput(
            "Email Address",
            "emailAddress",
            "email"
       )}
      ...
      <TouchableOpacity onPress={this.onLogin}>
         <Text>Submit</Text>
      </TouchableOpacity>
      )
   }
}

当我单击“提交”时,会发生错误

bug

2 个答案:

答案 0 :(得分:0)

您需要绑定方法,否则this没有作用域。在您的构造函数中添加:

    this.onLogin = this.onLogin.bind(this)

答案 1 :(得分:0)

您需要将this绑定到onLogin函数。

简单的方法是使用arrow函数,

onLogin = () => {   //Auto binds `this`
    const { email, password } = this.state;
    alert(email);
}

或者您可以使用constructor

constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
    this.onLogin = this.onLogin.bind(this)
}

注意:

您的renderInput函数带有4个参数,

renderInput = (
    placeholder: string,
    type: string,
    name: string,
    value: string
  ): Object => (

但是您只传递了3个参数,

{this.renderInput(
    "Email Address",   //This is placeholder
    "emailAddress",    //This is type
    "email"            //This is name
)}

这里type = emailAddress,我们没有emailAddress作为类型,它应该仅为email

您可以像这样简化输入,

<Input
   placeholder={placeholder}
   type={type}
   name={name}
   value={this.state[name] || value}
   onChangeText={(text) => this.setState({[name]: text})}
/>