简体   繁体   English

如何在 React 功能组件中正确使用 refs

[英]How to properly use refs in React functional components

The docs say this:文档是这样说的:

You may not use the ref attribute on function components because they don't have instances.您不能在函数组件上使用 ref 属性,因为它们没有实例。

Is this to say that we shouldn't be using refs anymore in React?这是说我们不应该再在 React 中使用 refs 了吗? What is the pattern for accessing the native DOM elements properly in functional react components if not refs?如果不是 refs,在功能性反应组件中正确访问本机 DOM 元素的模式是什么? This is so you can pass a ref to a function component, not to a native DOM tag.这样你就可以将 ref 传递给函数组件,而不是传递给原生 DOM 标签。

你可以像过去一样使用 document.getElementById()

The documentation says that you can use them in functional components, but not on them:文档说您可以功能组件中使用它们,但不能它们上使用:

const MyComponent = <div ref={OK} />
const SecondComponent = <MyComponent ref={N/A} />

Is this to say that we shouldn't be using refs anymore in React?这是说我们不应该再在 React 中使用 refs 了吗? No, you can still use ref with functional component.不,您仍然可以将 ref 与功能组件一起使用。

What is the pattern for accessing the native DOM elements properly in functional react components if not refs?如果不是 refs,在功能性反应组件中正确访问本机 DOM 元素的模式是什么? Forwarding refs .转发参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM