react怎么调用class类组件里面的某个函数?

在某个class类组件里面有一个方法,其他的组件中也需要,粘贴复制太low了,并且大大增加代码量,我想用导入导出的方法拿取到里面的方法,有大佬能告诉我吗

阅读 9.8k
4 个回答

可以把这个方法放到class上面用export导出,但是这样肯定不妥。 你应该把这个方法单独放到一个js文件里再分别导入。

使用ref可以拿到这个组件的实例,实例上可以找到这个方法的

试一下静态函数,静态函数可以用类名调用。

方法1:使用 ref 可以获取到组件 绑定到this 上的方法

// Video.js
class Video extends Component {
  ...

  play = () => {  
    this.setState({ isPlay: true })
  }
}


// page.js
...

class Page extends Component {
    
    videoInstance = null
    
    handlePlay = () => {
        // 调用某个组件内部函数
        this.videoInstance.play()
    }

    render() {
        return   <Video ref={(ref) => this.videoInstance = ref} />
    }
}

....

方法2:将复用部分抽象成高阶组件

function playHOC(WrappedComponent) {  
  return class Play extends React.Component { 
        
     play = () => {
        do something...
     }
    
    render() {      
      return <WrappedComponent {...this.props} play={this.play} />    
    }  
  } 
}

// 页面中

class Page extends Component {
    handlePlay =() => {    
        // 调用高阶组件中的方法
        this.props.play()
    }
}

playHOC(<Page>)

方法4: 定义 static 方法 缺点是无法访问this

方法3: hook 最推荐

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题