4

有沒有,你可以通過一個陣營的高階組件到傳遞上下文它包裝組件的方法嗎?通過一個HOC背景下做出反應的包裹組件

我有一個從其父接收範圍內,並利用這方面進行一個基本的,普遍的行動,然後包裝了一個子組件也需要訪問相同的情況下進行操作的HOC。例子:

HOC:

export default function withACoolThing(WrappedComponent) { 
    return class DoACoolThing extends Component { 
    static contextTypes = { 
     actions: PropTypes.object, 
    } 

    @autobind 
    doAThing() { 
    this.context.actions.doTheThing(); 
    } 

    render() { 
    const newProps = { 
     doAThing: this.doAThing, 
    }; 

    return (
     <WrappedComponent {...this.props} {...newProps} {...this.context} /> 
    ); 
    } 
}; 

裹組件:

import React, { Component } from 'react'; 
import PropTypes from 'prop-types'; 
import { autobind } from 'core-decorators'; 
import withACoolThing from 'lib/hocs/withACoolThing'; 


const propTypes = { 
    doAThing: PropTypes.func, 
}; 

const contextTypes = { 
    actions: PropTypes.object, 
}; 

@withACoolThing 
export default class SomeComponent extends PureComponent { 

    @autobind 
    doSomethingSpecificToThisComponent(someData) { 
    this.context.actions.doSomethingSpecificToThisComponent(); 
    } 

    render() { 
    const { actions } = this.context; 

    return (
     <div styleName="SomeComponent"> 
     <SomeOtherThing onClick={() => this.doSomethingSpecificToThisComponent(someData)}>Do a Specific Thing</SomeOtherThing> 
     <SomeOtherThing onClick={() => this.props.doAThing()}>Do a General Thing</SomeOtherThing> 
     </div> 
    ); 
    } 
} 

SomeComponent.propTypes = propTypes; 
SomeComponent.contextTypes = contextTypes; 

在HOC傳遞{...this.context}不起作用。 this.context作爲包裹部件由HOC包裹是空{}只要。請幫忙?有什麼辦法繼續傳承方面,不涉及把它當作道具?

回答

3

問題:

如果沒有定義contextTypes,那麼上下文將是一個空對象。

解決方案:

WrappedComponent.contextTypes的HOC。

說明:

在未定影的代碼,用於contextTypesSomeComponent未被設置。當SomeComponent獲得@withACoolThing的裝飾時,您對SomeComponent進行的任何更改實際上都發生在DoACoolThing之間,並且contextTypes對於SomeComponent永遠不會設置,因此它最終會成爲空對象{}

側面說明:

因爲你正在擴大在HOC this.context使其向下道具在這裏:

<WrappedComponent {...this.props} {...newProps} {...this.context} />

你應該有東西像子組件可用this.props.actions.doTheThing