【问题标题】:State isn't Updated in react native?状态在本机反应中没有更新?
【发布时间】:2018-10-18 19:04:28
【问题描述】:

我从上个月开始使用 react native 进行开发,并且我已经完成了一个练习项目,我遇到了一些问题,当我登录并 setState 更新我的状态时,它没有使用示例用户名和密码进行更新以进行测试。

关于某个问题的屏幕截图:

这是我的代码:

import React, { Component } from "react";
import { View, StyleSheet, Text, TextInput } from "react-native";

import Button from "./common/Button";
import Card from "./common/Card";
import CardItem from "./common/CardItem";
import Input from "./common/Input";

class Login extends Component {
      constructor(props) {
      super(props);
      this.state = { username: "anas", password: "123" };
      }

      handleLogin = () => {
           console.log(
                   `Email is: ${this.state.username} and pass is: ${this.state.password} .`
            );
      };
      render() {
           return (
             <View>
                <Card>
                   <CardItem>
                       <Input
                          label="Email: "
                          placeholder="Enter your Email.."
                          secureTextEntry={false}
                          onChangeText={username => this.setState({ 
                          username})}
                        />
                 </CardItem>
                 <CardItem>
                      <Input
                       label="Password: "
                       placeholder="Enter your password.."
                       secureTextEntry={true}
                       onChangeText={password => this.setState({ password})}
                      />
                 </CardItem>
                 <CardItem>
                    <Button btnTitle="Login" onPressHandle={this.handleLogin} 
                    />
                 </CardItem>
             <Text>Email: {this.state.username}</Text>
             <Text>pass: {this.state.password}</Text>
          </Card>
      </View>
    );
   }
 }
 export default Login;

【问题讨论】:

  • 你有什么问题?
  • 当我输入用户名并使用新值传递更新状态时需要
  • 我看到你已经这样做了。输入后可以使用 this.state.username 访问用户名
  • 您的Input 组件怎么样?您的代码适用于来自react-nativeTextInput 组件。
  • 我只是将组件分离到其他文件中并将它们导入到我的父文件中,当我使用“react-native”中的 TextInput 时它工作正常,但是当我使用我的 Input 组件时它不能正常工作?

标签: javascript reactjs react-native react-native-android react-native-navigation


【解决方案1】:

您的自定义 Input 组件中缺少 onChangeText 属性,因此请添加它。

<TextInput
    ...other props
    onChangeText={props.onChangeText}
/>

【讨论】:

  • 这是一个很好的收获!我完全错过了这张照片!
  • 谢谢@Wainage。
  • 是的,谢谢 :)
猜你喜欢
  • 2020-07-22
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
相关资源
最近更新 更多