javascript - 在 HOC 中访问 React 组件的功能

标签 javascript reactjs inheritance

我正在为我的各种 React 组件构建一个高阶组件。在这个 HOC 中,我需要访问 child 的方法并调用它们。我该怎么做?

示例 HOC:

export default function withHOC(Component) {
  return class extends React.Component {
    constructor(props) {
      super(props);
    }

    componentDidMount() {
      if (Component.someFunction) {
          Component.someFunction()
      }
    }

    render() {
      return <Component {...this.props} />;
    }
  };
}

示例组件:

class App extends React.Component {
  someFunction() {
    console.log("something done here, for example setState")
  }
  render() {
    return (
     <div></div>
    ); 
  }
}

// then it's used like this
export default withHOC(App)

我知道在某些情况下,像这样解决它甚至可能没有意义,但例如框架 Next.js 可以用它的 getInitialProps 函数做类似的事情。

最佳答案

既然你想调用HOC的componentDidMount中的子组件方法,一个更好的选择是确实调用组件本身的componentDidMount中的方法,这样可以解决当子组件没有功能,或者它由多个 HOC 组成,例如

export default function withHOC(Component) {
  return class extends React.Component {
    constructor(props) {
      super(props);
    }

    render() {
      return <Component {...this.props} />;
    }
  };
}

class App extends React.Component {
  componentDidMount() {
     this.someFunction();
  }
  someFunction() {
    console.log("something done here, for example setState")
  }
  render() {
    return (
     <div></div>
    ); 
  }
}

但是如果你仍然想在子组件中调用该函数,你可以使用 refs(但是如果 App 组件由其他 HOC 组成,这将不起作用)

export default function withHOC(Component) {
  return class extends React.Component {
    constructor(props) {
      super(props);
    }
    componentDidMount() {
         this.cmp.someFunction();
    }
    render() {
      return <Component ref={(ref) => this.cmp = ref} {...this.props} />;
    }
  };
}

class App extends React.Component {
  someFunction() {
    console.log("something done here, for example setState")
  }
  render() {
    return (
     <div></div>
    ); 
  }
}

关于javascript - 在 HOC 中访问 React 组件的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054368/

相关文章:

reactjs - 防止 Graphiql 控制台发出多个内省(introspection)查询

java - 哪个先执行,父构造函数还是子构造函数?

javascript - 从json中获取分层数据

javascript - 更改背景颜色

javascript - 访问 Angular.js 中同一 .factory 中的方法

reactjs - 使用 window.FileReader REACT 上传多个文件

javascript - 如何根据值获取期权的索引

reactjs - React限制嵌套更新的数量以防止无限循环

访问者在子类节点上的 C++ 访问者模式丢失 "is a"关系

delphi - 如何强制后代类实现抽象函数?