React 开发工具中组件的 forwardRef 是什么意思,我该如何使用它?

What does forwardRef by a component in React dev tools mean and how can I use it?

当我在 React 开发工具中检查组件结构时,我可以看到有一个 forwardRef 标记。我很困惑,因为在源代码中没有使用它的迹象。它是怎么存在的,我该如何使用它?

forwardRef 调用不在您自己的代码中,它们在您使用的包中。

styled.button 似乎来自 styled-components。此包使用 forwardRef 将您在样式按钮组件上设置的任何 ref 转发到基础 button 组件。你可以在他们的源代码中看到它 right here:

WrappedStyledComponent = ((React.forwardRef(forwardRef): any): IStyledComponent);

forwardRef 的使用从 styled-components v4 开始——参见 this migration guide 上的第 2 步:

Make sure your application is using react >= 16.3; internally we are using the new React.forwardRef API and new context APIs if you wish to try and polyfill for older React version support

在这个Tips and Tricks page上也有说明:

Refs to DOM nodes

styled-components makes use of the new React 16.3 API forwardRef. Thus, set refs like you would on any other component and they will automatically resolve to the underlying DOM element or wrapped component class instance.