解决使用装饰器导致ref失效问题

问题

由于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方法
}

参考文献

关于React使用装饰器后ref失效的问题解决方案
react-redux使用时利用ref调用子组件方法不可用报错

猜你喜欢

转载自blog.csdn.net/shadowfall/article/details/120174744