当前位置 博文首页 > momoda118的博客:react通过ref,让hooks使用class组件的方法

    momoda118的博客:react通过ref,让hooks使用class组件的方法

    作者:[db:作者] 时间:2021-08-16 22:04

    下图是class通过ref使用class组件的方法:

        <ComTableView
                onRef={(ref) => { this.TableView = ref }}//ref
              />
    

    如果要让hooks通过ref使用class组件的话,可以先声明一个全局变量TableView:

    var TableView;//全局定义
    const PushGroup = () => {
       //这里是你的hooks内容
    

    再在调用处这样写即可

            <ComTableView
                onRef={(ref) => { TableView = ref }}
            />
    

    被调用组件的写法
    直接在componeDidMount中将自己赋值与调用组件的方法中(与class使用class组件方法的写法一致)

      componentDidMount() {
        this.props.onRef(this);
      }
    
    cs