如何解决反应,将在父级创建的引用传递给子级
我正在重构代码,并且在父级中有一些逻辑,需要评估其子级中所有输入的值。为此,我在父级中创建4个引用,并将它们作为道具传递给它的子级。如下所示:
// References (will be used in multiple functions)
usernameInput = createRef(null);
emailInput = createRef(null);
passwordInput = createRef(null);
repeatPasswordInput = createRef(null);
...
render() {
return (
<View>
<Form1 usernameInputRef={usernameInput} emailInputRef={emailInput} />
<Form2 passwordInputRef={passwordInput} repeatPasswordInputRef={repeatPasswordInput} />
</View>
);
}
在每个孩子中,我都这样做:
// This is Child1. For Child2 gonna be the same but with its props.
const {
usernameInputRef,emailInputRef,} = props;
return (
<>
<TextInput
ref={usernameInputRef}
...
/>
<TextInput
ref={emailInputRef}
/>
</>
);
当我尝试访问父节点中每个子节点的值时出现问题……如果这样做:
const username = this.usernameInput.current.props.value; // <--- Works if the input is in the same component,and not in the child.
console.log(username);
我得到“ null”。
有什么想法吗?在将我的代码重构为多个组件之前,这是可行的...
更新
TextInput代码:
import React from "react";
import { View,StyleSheet } from "react-native";
import { TextInput as RNPTextInput,useTheme } from "react-native-paper";
const TextInput = forwardRef((props,ref) => {
const { colors } = useTheme();
let {
placeholder,multiline,maxLength,secureTextEntry,color,icon,counter,onChange,onSubmit,onFocus,containerStyle,} = props;
...
return (
<>
<View style={containerStyle || styles.inputContainer}>
<RNPTextInput
ref={ref}
...
解决方法
有一个优雅的解决方案,可以从孩子那里访问数据。只需将forwardRef与useImperativeHandle挂钩结合即可。
执行此操作:
const TextInput = forwardRef((props,ref) => {
useImperativeHandle(ref,() => ({
getText() {
return text;
},}));
而不是使用以下内容处理文本:
const username = this.usernameInput.current.props.value
您将可以通过以下方式获取它:
const username = this.usernameInput.current.getText();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。