繁体   English   中英

无法使用 onChangeText 在反应本机组件中更新 state

[英]Unable to update state in react native component using onChangeText

我一直在尝试在提交表单时更新 email 和密码值,以便我可以在我的登录 API 参数中传递它们。 但是我已经尝试了几乎所有东西, this.state的值不会只是更新。 每次我尝试在控制台日志中打印值时,例如: cosole.log(this.state.email) ,它都会打印空字符串,即之前设置的默认值。 下面是我的代码:

login.js

import React, { Component } from 'react';
import { ThemeProvider, Button } from 'react-native-elements';
import BliszFloatingLabel from './BliszFloatingLabel'

import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Animated,
  ImageBackground,
  Linking
} from 'react-native';
const  domain = 'http://1xx.xxx.xx.xxx:8000';
class Login extends Component {

    state = {
      email: '',
      password: '',
    }

  LoginAPI = (e,p) => {
    console.log(e, "####")
 }

  handleEmail = (text) => {
    this.setState({ email: text })
 }
  handlePassword = (text) => {
    this.setState({ password: text })
 }
  goToSignUpScreen=() =>{
    this.props.navigation.navigate('SignUpScreen');

  };
  goToForgotPasswordScreen=() =>{
    this.props.navigation.navigate('ForgotPasswordScreen');

  };
  render() {
    return (

      <View style={styles.container} >
        <ImageBackground source={require('../bgrndlogin.jpeg')} style={styles.image} >
          <View style={styles.heading}>
            <Image style={styles.logo} source={require('../loginlogo.png')} />
            <Text style={styles.logoText}>Login</Text>
            <Text style={styles.logodesc}>Please Login to continue --></Text>
          </View>

          <View style={styles.form_container}>

            <BliszFloatingLabel
              label="Email Id"
              value={this.state.email}
              onChangeText = {this.handleEmail}
              onBlur={this.handleBluremail}

            />
            <BliszFloatingLabel
              label="Password"
              value={this.state.password}
              onChangeText = {this.handlePassword}
              onBlur={this.handleBlurpwd}
              secureTextEntry={true}
            />
            <ThemeProvider theme={theme}>
              <Button buttonStyle={{
                opacity: 0.6,
                backgroundColor: '#CC2C24',
                borderColor: 'white',
                borderWidth: 1,
                width: 200,
                height: 50,
                marginTop: 30,
                marginLeft: '20%',
                alignItems: 'center',
                justifyContent: "center"

              }}
                title="Login"
                type="outline"
                onPress = {
                  () => this.LoginAPI(this.state.email, this.state.password)
               }
              />
            </ThemeProvider>
            <Text style={{
              marginTop: 70,
              color: '#CC2C24',
              fontSize: 16,
              fontWeight: "bold"
            }}
            onPress={
              this.goToForgotPasswordScreen 
              }>
              Forgot Password?
          </Text>
            <Text style={{
              marginTop: 20,
              color: '#CC2C24',
              fontSize: 16,
              fontWeight: "bold"
            }}
            onPress={
              this.goToSignUpScreen 
              }>
              Don't have an Account?
          </Text>
          </View>
        </ImageBackground>
      </View>
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  logo: {
    width: 115,
    height: 50,

  },
  logoText: {
    color: 'white',
    fontSize: 36,
    fontWeight: "bold"
  },
  logodesc: {
    color: '#CC2C24',
    fontSize: 18,
    fontWeight: "bold"

  },
  heading: {
    flex: 3,
    marginLeft:20,
    marginTop:30
  },
  form_container: {
    flex: 7,
    marginLeft:20,
    marginTop:30,
    marginRight: 20,
  },
  image: {
    flex: 1,
    resizeMode: "cover",
    justifyContent: "center"
  },
});
const theme = {
  Button: {
    titleStyle: {
      color: 'white',
      fontWeight: "bold",
      fontSize: 18
    },
  },
};

export default Login;

我创建了一个通用表单,如下所示,我在所有地方都继承了它:BliszFloatingLabel.js

import React, { Component } from 'react';

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

class BliszFloatingLabel extends Component {
    state = {
      entry: '',
      isFocused: false,
    };
    UNSAFE_componentWillMount() {
      this._animatedIsFocused = new Animated.Value(0);
    }
    handleInputChange = (inputName, inputValue) => {
      this.setState(state => ({ 
        ...state,
        [inputName]: inputValue // <-- Put square brackets
      }))
    }

    handleFocus = () => this.setState({ isFocused: true })
    handleBlur = () => this.setState({ isFocused: true?this.state.entry!='' :true})
    handleValueChange = (entry) => this.setState({ entry });
    componentDidUpdate() {
      Animated.timing(this._animatedIsFocused, {
        toValue: this.state.isFocused ? 1 : 0,
        duration: 200,
        useNativeDriver: true,
      }).start();
    }
    render() {
      // console.log(this.state.entry)
      const { label, ...props } = this.props;
      const { isFocused } = this.state;
      const labelStyle = {
        position: 'absolute',
        left: 0,
        top: !isFocused ? 40 : 0,
        fontSize: !isFocused ? 16 : 12,
        color: 'white',
      };
      return (
        <View style={{ paddingTop: 20,paddingBottom:20 }}>
          <Text style={labelStyle}>
            {label}
          </Text>
          <TextInput
            {...props}
            style={{
              height: 50, fontSize: 16, color: 'white', borderBottomWidth: 1, borderBottomColor: "white"
            }}
            value={this.state.entry}
            onChangeText={this.handleValueChange}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
            blurOnSubmit
          />
        </View>


      )
    }
  }
  export default BliszFloatingLabel;

而不是像这样传递 onChangeText onChangeText={this.handleValueChange}BliszFloatingLabelLogin组件中传递一个回调。

onChangeText={(text)=>this.handleValueChange(text)}

小吃与夹具。

https://snack.expo.io/@waheed25/d16fb3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM