在打字稿中反应高阶组件(HOC)

时间:2017-04-07 13:50:32

标签: reactjs typescript higher-order-components

我正在尝试用打字稿写一个React HOC,但我没有得到正确的定义。我不确定我想要完成的是否可能。

这是我的代码

import * as React from 'react'

export default function Ajax<Props, State>(InnerComponent: typeof React.Component): React.ComponentClass<Props & State> {
  return class extends InnerComponent<Props & State,any> {
    constructor() {
      super()
      this.state = {
        request: 'initial'
      }
    }
    changeRequest(newRequest) {
      this.setState({request: 'loading'})
    }
    render() {
      return <InnerComponent 
        {...this.props } 
        {...this.state}
        changeRequest={this.changeRequest} 
      />
    }
  }
}

如果我只是将道具和状态传递给孩子,那就有效了。但是,如何编写定义以便能够将其他道具传递给包装组件?在这种情况下,changeRequest prop。

由于

2 个答案:

答案 0 :(得分:3)

我能够让它发挥作用。但我不确定这是正确的方法。但是现在编译器没有抱怨并且代码有效。 对于编译器停止抱怨我必须将道具添加为javascript对象。

这是我的工作代码:

import * as React from 'react'

export default function Ajax<Props, State> (InnerComponent: typeof React.Component): React.ComponentClass<Props & State> {
  return class extends InnerComponent<Props & State, any> {
    constructor() {
      super()
      this.state = {
        request: 'initial'
      }
      this.changeRequest = this.changeRequest.bind(this)
    }
    changeRequest(newRequest) {
      this.setState({request: 'loading'})
    }
    render() {
      return <InnerComponent {...this.props} {...this.state} {...{onCLick: this.changeRequest}}/>
    }
  }
}

答案 1 :(得分:0)

我相信你只需要将HOC的上下文绑定到changeRequest函数。

constructor() {
  ...
  this.changeRequest = this.changeRequest.bind(this)
}

确保你在InnerComponent处理道具。例如。
<InnerComponent onClick={this.props.changeRequest}>

相关问题