forwardRef
调用不在你自己的代码中,而是在你使用的包中。
styled.button
看起来来自于 styled-components
。这个包使用 forwardRef
来将你在 styled button 组件上设置的任何 ref
转发到底层的 button
组件。你可以在他们的源代码这里看到。WrappedStyledComponent = ((React.forwardRef(forwardRef): any): IStyledComponent);
forwardRef
的用法始于 styled-components v4 -- 可参考 此迁移指南 的第2步骤:
确保您的应用程序使用 react >= 16.3;我们在内部使用新的
React.forwardRef
API 和新的上下文API,如果您希望尝试为旧的React版本支持进行 polyfill,请使用它们。
这也在 技巧页面 上有解释:
DOM节点的引用 (Refs to DOM nodes)
styled-components 使用新的 React 16.3 API
forwardRef
。因此,像在任何其他组件上一样设置 refs,并且它们将自动解析为底层 DOM 元素或包装的组件类实例。
forwardRef
来让你访问库中包装器内部的元素。提供一些代码以更好地理解。 - strdr4605