javascript - React,将在父级创建的引用传递给子级
问题描述
我正在重构我的代码,并且我在父级中有一些逻辑,需要评估其子级的所有输入的值。为此,我在父级中创建了 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);
我得到“空”。
有任何想法吗?这是在将我的代码重构为多个组件之前工作的......
更新
文本输入代码:
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();
推荐阅读
- java - 如何从 Activity2 的按钮更改 Activity1 的 actionBar 标题
- php - PayPal Webhook 不发送 POST 数据
- vb.net - vb.net NAudio.dll - 未定义类型“AudioFileReader”
- java - Android:如何判断月份是否早于一天
- java - 如何将方法参数中的值存储到数组中?
- hadoop - Apache Flink:可用任务槽 0
- slack - 无法通过 Slack API 成功上传文件
- python - 为什么要使用详细标志来运行特定的单元测试?
- docker - 多个域的 certbot webroot 仅返回一个证书
- python - 不同分辨率的两个时间序列之间的最大差异