Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

reactjs - Why you can't pass a ref to a functional component in react?

Why you can't pass a ref to a functional component in react?

What is different in function components compared to class components that you can't pass a ref to it?

Why is that not possible?

Notes: I'm making this question, because I always saw explanations about how to use ref with functional components, and that you need to use fowardRef, but no one explained how react handles functional components making it not possible to pass a ref to it, it's always explained how to do it, but never why you need to do it.

question from:https://stackoverflow.com/questions/65918223/why-you-cant-pass-a-ref-to-a-functional-component-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two aspects:

  • Function components don't have ref attribute because they don’t have instances like class components. Therefore you must FORWARD THE REF to any other element within it.
  • You can't use the ref prop as it reserved.

You can, however, use another prop name like innerRef and use if for forwarding.

Check a more detailed answer with examples: Why, exactly, do we need React.forwardRef?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...