我正在尝试在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>
);
}
答案 0 :(得分:0)
您的固定方式可能如下:
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钩子使用具有调用它的元素的新文本值来调用该函数,因此我们仍然必须区分状态中要更新的参数。