在打字稿中反应高阶组件(HOC)
我想在打字稿中写一个React HOC,但我没有得到正确的定义。我不知道我是否有可能实现自己的目标。在打字稿中反应高阶组件(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支柱。
谢谢
我相信你只需要将HOC的上下文绑定到changeRequest函数。
constructor() {
...
this.changeRequest = this.changeRequest.bind(this)
}
并确保您在处理InnerComponent
中的道具。例如。 <InnerComponent onClick={this.props.changeRequest}>
嗨保罗, 感谢您的答复。 这不是关于绑定上下文。你需要绑定才能使点击工作。但我的问题在于类型。 –
啊,明白了。真高兴你做到了。 – paul
我能够使它发挥作用。但我不确定这是否正确。但是现在编译器不会抱怨,代码可以工作。 对于编译器停止抱怨,我不得不添加道具作为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}}/>
}
}
}
我不知道哪里出了问题。被包装的组件需要知道所有的属性,你不应该在HOC中扩展它的属性定义。 – niba