在React中,想要在父组件引用子组件的属性或方法就需要使用ref将子组件的组件实例在父组件中引入。
但是如果子组件export的是使用react-redux库的connect函数封装的话
export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent)
在父组件render函数中渲染子组件
<ChildComponent ref={this.childComponent = ref} />
时获取ref会报错,提示
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
这个原因是connect函数是会使用一个匿名父组件render被包裹元素,而这个匿名父组件还会在一个外部function中被返回,而React不允许渲染function组件的事件引入ref,所以报warning,父组件的childComponent变量肯定也拿不到东西。
怎么样解决这个问题就是需要将内部的子组件ref透传出来,在以前的react-redux版本中,connect函数的第四个参数options对象可以将withRef置为true,这样connected的新匿名组件就会将ref传递到被包裹的子组件中,开发者渲染的connected component就可以拿到目标子组件的ref实例,故