2017-04-07 70 views
2

我想在打字稿中寫一個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支柱。

謝謝

+0

我不知道哪裏出了問題。被包裝的組件需要知道所有的屬性,你不應該在HOC中擴展它的屬性定義。 – niba

回答

0

我相信你只需要將HOC的上下文綁定到changeRequest函數。

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

並確保您在處理InnerComponent中的道具。例如。
<InnerComponent onClick={this.props.changeRequest}>

+0

嗨保羅, 感謝您的答覆。 這不是關於綁定上下文。你需要綁定才能使點擊工作。但我的問題在於類型。 –

+0

啊,明白了。真高興你做到了。 – paul

2

我能夠使它發揮作用。但我不確定這是否正確。但是現在編譯器不會抱怨,代碼可以工作。 對於編譯器停止抱怨,我不得不添加道具作爲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}}/> 
    } 
    } 
}