Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[腾讯一面]React中ref转发 #48

Open
sufuwang opened this issue Mar 31, 2020 · 1 comment
Open

[腾讯一面]React中ref转发 #48

sufuwang opened this issue Mar 31, 2020 · 1 comment

Comments

@sufuwang
Copy link

我期望的重点:ref转发的使用场景
非常感谢您的回答。

@ZhaoTim
Copy link

ZhaoTim commented Jul 3, 2020

可以用于获取函数式组件的ref

const ref = React.createRef();
<FunComp ref={ref} />

由于FunComp是函数式组件,没有实例,所以我们没有办法获得函数式组件的ref,在这我们就可以使用ref转发来解决:

const FunComp = React.forwardRef((props, ref) => (
 // 内部为FunComp组件的实现逻辑,在这里面你可以把ref赋值给你想赋值的DOM节点
));

之后你就可以直接在FunComp组件传ref了:

<FunComp ref={ref} />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants