在使用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
啦~
网友评论