ReactforwardRef - 访问组件内和父级中的引用

Set*_*ske 11 javascript reactjs react-forwardref

我需要访问组件内文本区域的引用。在组件内,它很简单:

const MyComponent = () => {
  const inputRef = useRef();

  return <textarea ref={inputRef} />
}
Run Code Online (Sandbox Code Playgroud)

现在 ref 在 MyComponent 中可用,我可以将它用于一些内部逻辑。

在某些情况下,我也需要从父组件访问引用。在这种情况下,我可以使用forwardRef:

const MyComponent = React.forwardRef((props, ref) => {
  return <textarea ref={ref} />
})

// In some parent
const MyParent = () => {
  const inputRefFromParent = useRef();
  return <MyComponent ref={inputRefFromParent} />
}
Run Code Online (Sandbox Code Playgroud)

现在我可以从父组件访问 ref textarea,并将其用于父组件中的逻辑。

我发现自己处于这样的情况:我需要使用 中的 ref 进行一些内部逻辑MyComponent,但我可能还需要从 中获取该引用MyParent。我怎样才能做到这一点?

Ami*_*era 19

您可以ref在 中MyComponent保留 ,并使用useImperativeHandle钩子使用refMyParent.

尝试如下所示。它将文本区域中的焦点方法公开给父级。您还可以通过访问 来执行任何其他内部操作textAreaRef

import { useRef, forwardRef, useImperativeHandle } from "react";

const MyComponent = forwardRef((props, ref) => {
  const textAreaRef = useRef();

  // all the functions or values you can expose here
  useImperativeHandle(ref, () => ({
    focus: () => {
      textAreaRef.current.focus();
    }
  }));

  const internalFunction = () => {
    // access textAreaRef
  };

  return <textarea ref={textAreaRef} />;
});

// In some parent
const MyParent = () => {
  const inputRefFromParent = useRef();

  // you can call inputRefFromParent.current.focus(); in this compoenent
  return <MyComponent ref={inputRefFromParent} />;
};
Run Code Online (Sandbox Code Playgroud)


Set*_*ske 8

除了阿米拉的回答之外,我还找到了另一种方法,即使用ref 回调

const MyComponent = React.forwardRef((props, parentRef) => {
  const localRef = useRef();
  return <textarea ref={ref => {
    parentRef.current = ref;
    localRef.current = ref;
  }} />
})
Run Code Online (Sandbox Code Playgroud)

因此,回调 ref 对 ref 保持更细粒度的控制textarea,并简单地将其值分配给本地引用和父引用。

  • 如果您使用打字稿,对于“parentRef”,您必须使用类似“if (typeofparentRef ===“function”)parentRef(ref); 的内容。else if (parentRef !== null)parentRef.current = ref;` (5认同)