问题
由于react的升级导致了之前的refs的无法使用,使用createRef创建ref的方式进行修改代码,发现ref无法获取到子组件的实例
原因
React在使用装饰器装饰过后ref就失效了,因为该this指向了所用的装饰器,所以在使用ref时会找不到我们所要使用的子组件的current,因此可以模拟fowradRef将ref包装成一个函数向下传递到我们要使用的子组件上再执行。
解决方法
方案一
- 在工具中添加一个方法:
import React from 'react';
export default const getRef = ChildComponent => {
return props => {
const {
getRef, ...otherProps } = props
return <ChildComponent ref={
getRef} {
...otherProps} />
}
}
- 在子组件中导入使用
import {
getRef } from '~/common/utils';
const mapState = state => ({
searchCIList: state.searchCIList
});
@connect(mapState)
@getRef
export default class ChildrenItem extends Component {
...
}
- 在父组件的使用
<MyFilter
getRef={
ref => (this.sharedfilter = ref)}
...
/>
方案二
- 如果不想写高阶函数,可以直接在子组件的初始化时将this传递给父组件的getRef,父组件和方案一一样。
componentDidMount(){
this.props.getRef(this)//将组件实例this传递给onRef方法
}