美文网首页
2020-05-28 Function components c

2020-05-28 Function components c

作者: KingAmo | 来源:发表于2020-05-28 19:49 被阅读0次

在使用ref时遇到报错 Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

但是我明明是对class组件使用ref啊?怎么会报错对 Function组件使用ref呢?
别急,仔细看代码,我们在class组件中使用了redux,并用 react-redux提供的connect高阶函数包裹了class组件,就是因为connect方法,导致我们export出去的是高阶函数式组件。而函数式组件目前是无法使用ref的。

如何解决这种使用场景呢?其实文档中已经对这种使用场景提供方法了:react-redux 文档

使用方法:

export default connect(mapStateToProps, null, null, { forwardRef: true })(ClassComponent);

这样我们又可以愉快的使用ref啦~

相关文章

网友评论

      本文标题:2020-05-28 Function components c

      本文链接:https://www.haomeiwen.com/subject/slxvahtx.html