javascript - React,将父级创建的引用传递给子级

标签 javascript reactjs react-native components

我正在重构我的代码,并且父级中有一些逻辑需要评估其子级拥有的所有输入的值。为此,我在父级中创建 4 个引用,并将它们作为 prop 传递给其子级。如下:

  // 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>
     );
  }

在每个 child 身上,我都这样做:

  // 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”。

有什么想法吗?在将我的代码重构为多个组件之前,这是有效的......

更新

文本输入代码:

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}
          ...

最佳答案

有一个优雅的解决方案可以访问 child 的数据。只需将forwardRef 与useImperativeHandle Hook 结合起来即可。

这样做:

const TextInput = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getText() {
      return text;
    },
  }));

不要用以下方式访问文本:

 const username = this.usernameInput.current.props.value

您可以通过以下方式获得它:

const username = this.usernameInput.current.getText();

这是一个完整的示例:https://medium.com/@nugen/react-hooks-calling-child-component-function-from-parent-component-4ea249d00740

关于javascript - React,将父级创建的引用传递给子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63674766/

相关文章:

javascript - 如何处理谷歌街景API响应

javascript - 更改 JavaScript 中 forEach 循环的每次迭代的颜色?

javascript - XML 使用 jQuery 删除文本不等于的元素

javascript - 使用 ReactJS 传递 props

javascript - Console.log 不适用于 Reactjs 应用程序

javascript - React Native - 显示键盘并渲染其值而不使用输入

javascript - 在 Javascript/JQuery 中访问/修改 Ruby 类属性

javascript - 我不确定为什么当我查看 JS Mixin 模式教程时没有定义 `Logger`

javascript - 需要在 yup 最小和最大验证消息中引用/访问 Yup.ref() 值

android - getCurrentActivity 不是公开的 'com.facebook.react.bridge.React Context` 无法从外部包访问