【问题标题】:React, pass a reference created at the parent to the childrenReact,将在父级创建的引用传递给子级
【发布时间】:2020-12-19 19:21:54
【问题描述】:

我正在重构我的代码,并且我在父级中有一些逻辑,需要评估其子级所具有的所有输入的值。为此,我在父级中创建了 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}
          ...

【问题讨论】:

  • TextInput 对ref 做了什么,它是否支持转发refs? reactjs.org/docs/forwarding-refs.html
  • @Aivaras 我已经用 TextInput 代码更新了这个问题。基本上这是 react-native-paper TextInput 的包装

标签: javascript reactjs react-native components


【解决方案1】:

有一个优雅的解决方案可以从孩子那里访问数据。只需将 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();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2020-12-31
    • 2023-01-13
    相关资源
    最近更新 更多