2

我正在尝试用打字稿编写 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 道具。

谢谢

4

2 回答 2

3

I was able to make it work. But I am not sure this is the correct way. But now the compiler is not complaining and the code works. For the compiler stop complaining I had to add the props as javascript Objects.

Here is my working code:

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}}/>
    }
  }
}
于 2017-04-07T17:43:14.257 回答
0

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

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

并确保您正在处理InnerComponent. 例如。
<InnerComponent onClick={this.props.changeRequest}>

于 2017-04-07T14:26:01.707 回答