【问题标题】:Redirect refs from children component to the parent in ReactJs将引用从子组件重定向到 ReactJs 中的父组件
【发布时间】:2025-12-18 10:55:01
【问题描述】:

我在 react js 中有我的父组件:

import React from 'react';

const MyComponent = () => {
    const myRef = React.createRef();

    const childrenprops = React.Children.map(children, (child) => {
        return React.cloneElement(child, {
            myRef
        });
    });
    return (
        <div>
            {childrenprops}
        </div>
    );
};

export default MyComponent;

还有子组件:

import React from 'react';

const Child = forwardRef((props, myRef) => {
    const myRef = React.createRef();

    return (
        <div>
           ... ... ..
        </div>
    );
};

export default Child;

&lt;Child/&gt; 组件保留,而不是 &lt;MyComponent/&gt; 中的 children。接下来是问题:当我从子组件保存数据时,我在 MyComponent 中没有得到任何东西,所以我没有在父组件中得到 ref。问:forwardref我用对了吗?

注意:我看过很多例子,但在我这边是行不通的。

【问题讨论】:

  • React refs 本身不是 props,所以你不能用 props 克隆它们,但是 docs 确认原始元素上的任何 refs 都会被保留。您也只创建了一个 ref,因此只有最后一个接收 ref 的组件才是它的当前值。如果您只是尝试将 ref 传递给每个孩子,那么您需要为每个孩子创建一个。我也不认为cloneElement 是必要的,但是您的示例代码非常少,因此您的用例上下文很少甚至不存在。明发布一个更完整的例子?
  • @DrewReese,这是我的应用程序 codesandbox.io/s/react-editor-js-forked-tc0gh?file=/Parent.js 的结构。这个想法是我只想在父组件的save 函数中保存数据,所以我需要将一个引用传递给子组件,并从编辑器和数据数据中保存日期以显示在保存函数中。你能帮忙吗?这是一个传递 ref 的方法,但是如果传递 props trought children github.com/Jungwoo-An/react-editor-js 则不起作用。谢谢

标签: reactjs


【解决方案1】:

孩子

每个孩子都应该拥有自己的对编辑器实例的反应引用。关注此example。子组件应该收到一个回调 prop,用于将数据发送回父组件。

const Child = ({ onSave }) => {
  const instanceRef = React.useRef(null); // <-- (1) create ref

  const onClick = async () => onSave(await instanceRef.current.save()); // <-- (4) pass the saved data to callback

  return (
    <div>
      <EditorJs
        data={.....}
        instanceRef={(instance) => (instanceRef.current = instance)} // <-- (2) save current value of editor instance
      />
      <button type="button" onClick={onClick}> // <-- (3) attach click handler
        click
      </button>
    </div>
  );
};

家长

使用 React * API 中的 ChildrencloneElement 映射 children 属性并注入 onSave 属性。

const MyComponent = ({ children }) => {
  const save = (data) => {
    console.log(data);
  };

  return (
    <div>
      <h1>parent</h1>
      {Children.map(children, (child) => cloneElement(child, { onSave: save }))}
    </div>
  );
};

然后用父组件包裹子组件。

class ReactEditor extends Component {
  render() {
    return (
      <Parent>
        <Child />
      </Parent>
    );
  }
}

演示

【讨论】: