当我在 React 开发工具中检查组件结构时,我可以看到有一个forwardRef
标记。我很困惑,因为源代码中没有使用它的迹象。它是怎么存在的以及我该如何使用它?
The forwardRef
调用不在您自己的代码中,它们在您正在使用的包中。
styled.button
似乎来自styled-components
。这个包使用forwardRef
转发任何ref
您在样式化按钮组件上设置的底层button
成分。你可以在他们的源代码中看到它就在这儿 https://github.com/styled-components/styled-components/blob/404190e26062133a7b916d73c1d52312db20bc92/packages/styled-components/src/models/StyledComponent.js#L252:
WrappedStyledComponent = ((React.forwardRef(forwardRef): any): IStyledComponent);
的用法forwardRef
从 styled-components v4 开始——参见步骤 #2本迁移指南 https://styled-components.com/docs/faqs#what-do-i-need-to-do-to-migrate-to-v4:
确保您的应用程序使用的是 React >= 16.3;在内部我们正在使用新的React.forwardRef
API 和新的上下文 API(如果您想尝试使用 polyfill 来支持较旧的 React 版本)
对此也有说明提示和技巧页面 https://github.com/styled-components/styled-components/blob/72a6f642c3dedbcee91a2b5d76f96b93f345b86f/packages/styled-components/docs/tips-and-tricks.md#refs-to-dom-nodes:
对 DOM 节点的引用
styled-components 使用新的 React 16.3 APIforwardRef
。因此,像在任何其他组件上一样设置 refs,它们将自动解析为底层 DOM 元素或包装的组件类实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)