【发布时间】:2020-02-17 20:25:39
【问题描述】:
我在我的应用中尝试做的是登录表单。
当用户在令牌输入字段中输入内容时:
<Input
secureTextEntry
ref={token1}
maxLength={1}
onChange={(e) => this.tokenChange(e, token2)}
/>
而tokenChange函数是这样的:
tokenChange = (e, nextToken) => {
if (nextToken) {
if (nextToken.current) {
if (e.target.value != '') {
nextToken.current.focus();
}
setToken(token1.current.value + token2.current.value + token3.current.value + token4.current.value);
}
}
}
将选择下一个输入。一切正常,我申请 useRef() 以了解我当前关注的令牌,并且我也在尝试将其应用于 Button 元素。
const token1 = useRef();
const token2 = useRef();
const token3 = useRef();
const token4 = useRef();
const submitBtn = useRef();
当我试图专注于按钮时,问题就出现了。我在输入和按钮中都使用了ref={},但我不知道我做错了什么,因为我在文档中没有找到任何东西。就像输入一样,我将引用链接到按钮,如下所示:
<Button
raised
title={tituloBtn}
ref={submitBtn}
onPress={() => onSubmit(email, password)}
/>
所以,我正在运行我的应用程序,我可以从一个输入传递到另一个输入,但是当从第四个令牌传递到提交按钮时,我收到此错误:
这是我的功能组件的通用代码:
const FormLogin = ({ titulo, tituloBtn, onSubmit, estadoApp }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [token, setToken] = useState('');
const token1 = useRef();
const token2 = useRef();
const token3 = useRef();
const token4 = useRef();
const submitBtn = useRef();
tokenChange = (e, nextToken) => {
if (nextToken) {
if (nextToken.current) {
if (e.target.value != '') {
nextToken.current.focus();
}
setToken(token1.current.value + token2.current.value + token3.current.value + token4.current.value);
}
}
}
return (
<View style={estilos.contenedor}>
<Text style={estilos.titulo} h3>{titulo}</Text>
<Espaciador />
<Input
placeholder="correo@ejemplo.com"
value={email}
onChangeText={setEmail}
keyboardType='email-address'
autoCapitalize="none"
autoFocus
label="Ingresa tu correo"
leftIcon={
<MaterialIcons
style={estilos.icon}
name="email"
/>
}
/>
<Espaciador />
<Input
placeholder="******"
value={password}
onChangeText={setPassword}
secureTextEntry
clearTextOnFocus
autoCapitalize="none"
label="Ingresa tu contraseña"
leftIcon={
<Ionicons
style={[estilos.icon, {fontSize: 35}]}
name="md-lock"
/>
}
/>
<View style={estilos.tokenGroup}>
<Input
style={estilos.token}
secureTextEntry
keyboardType='numeric'
ref={token1}
maxLength={1}
onChange={(e) => this.tokenChange(e, token2)}
/>
<Input
style={estilos.token}
secureTextEntry
keyboardType='numeric'
ref={token2}
maxLength={1}
onChange={(e) => this.tokenChange(e, token3)}
/>
<Input
style={estilos.token}
secureTextEntry
keyboardType='numeric'
ref={token3}
maxLength={1}
onChange={(e) => this.tokenChange(e, token4)}
/>
<Input
style={estilos.token}
secureTextEntry
keyboardType='numeric'
ref={token4}
maxLength={1}
onChange={(e) => this.tokenChange(e, submitBtn)}
/>
</View>
{estadoApp.errorMensaje
? <Text style={estilos.error}>{estadoApp.errorMensaje}</Text>
: null}
<Espaciador />
<Button
raised
title={tituloBtn}
ref={submitBtn}
onPress={() => onSubmit(email, password)}
/>
</View>
);
};
【问题讨论】:
标签: javascript react-native reference react-hooks ref