React Higher Order Component - 来自包装器组件的包装组件中的call函数

时间:2017-09-16 16:19:40

标签: javascript reactjs higher-order-components

假设我使用了正确的模式,我希望能够从someFunc()内部呼叫<Home/> - 位于<Wrapper/>内部。见下文:

var Home = React.createClass({
  someFunc() {
    console.log('How can I call this from <Wrapper/>?')
  },
  render() {
    return <h1>Hello World</h1>
  }
})

var Wrapper = (Home) => {
  return React.createClass({
    render() {
      return <Home {...this.props}/>
    }
  })
}

var HomeWrapped = Wrapper(Home)

ReactDOM.render(<HomeWrapped/>, document.getElementById('root'))

使用解决方案更新https://codepen.io/oldgithub/pen/qPOZEj

1 个答案:

答案 0 :(得分:1)

您可以使用ref

var Wrapper = (Home) => {
  return React.createClass({
    render() {
      return (
          <div>
              <button onClick={() => {this.home.someFunc()}} />
              <Home
                  {...this.props}
                  ref={(c) => this.home = c;}
              />
          </div>
      );
    }
  })
}