【问题标题】:global onChange handler in react nativereact native 中的全局 onChange 处理程序
【发布时间】:2020-07-06 00:38:32
【问题描述】:

我正在尝试在 react-native 中创建一个全局 onchange 处理程序 但它没有将我的电子邮件和密码的值设置为我输入的任何内容 我试过在谷歌上搜索,但大多数例子都是基于 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>
  );
}

【问题讨论】:

    标签: javascript react-native onchange use-state


    【解决方案1】:

    您的方式可能固定如下:

    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 钩子使用调用它的元素的新文本​​值调用函数,因此我们仍然需要区分状态中要更新的参数。

    【讨论】:

    • 我非常感谢这个解决方案,我已经有超过 18 小时的时间试图找到问题的解决方案,只有您的解决方案被证明是富有成效的。再次感谢
    • 随时。快乐的黑客攻击!
    猜你喜欢
    • 2022-12-24
    • 2020-01-06
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多