React Native 中的全局 onChange 处理程序

global onChange handler in react native

我正在尝试在 react-native 中创建一个全局 onchange 处理程序 但它不会将我的电子邮件和密码的值设置为我输入的任何值 我试过在 google 上搜索,但大多数示例都是基于 react.js 而不是 react-native 我将不胜感激

import React, {useState} from 'react';
import {View, Text, Button, TextInput} from 'react-native';
import style from './Style';

export default function Login() {
  const [authDetails, setAuthDetails] = useState({
    email: '',
    password: '',
  });

  const {email, password} = authDetails;

  const onChange = text =>
    setAuthDetails({
      ...authDetails,
      email: text.email,
      password: text.name,
    });
  const login = () => {
    console.log('EMAIL=', email, '\n', 'password =', password);
  };

  return (
    <View>
      <TextInput
        name="email"
        placeholder="Email"
        onChangeText={onChange}
        value={email}
      />

      <TextInput
        name="password"
        placeholder="Password"
        onChangeText={onChange}
        value={password}
      />
      <Button title="Login" onPress={login} />
    </View>
  );
}

您的方式可能会被修正如下:

import React, {useState} from 'react';
import {View, Text, Button, TextInput} from 'react-native';
import style from './Style';

export default function Login() {
  const [authDetails, setAuthDetails] = useState({
    email: '',
    password: '',
  });

  const {email, password} = authDetails;

  const onChange = update =>
    setAuthDetails({
      ...authDetails,
      ...update
    });
  const login = () => {
    console.log('EMAIL=', email, '\n', 'password =', password);
  };

  return (
    <View>
      <TextInput
        name="email"
        placeholder="Email"
        onChangeText={text => onChange({ email: text }) }
        value={email}
      />

      <TextInput
        name="password"
        placeholder="Password"
        onChangeText={text => onChange({ password: text }) }
        value={password}
      />
      <Button title="Login" onPress={login} />
    </View>
  );
}

从上面的代码可以看出,onChangeText 钩子使用调用它的元素的新文本​​值调用函数,因此我们仍然必须区分要在状态中更新的参数。