4

リアクションの上位コンポーネントからラップするコンポーネントにコンテキストを渡す方法はありますか?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} /> 
    ); 
    } 
}; 

包まれたコンポーネント:HOCに{...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; 

は動作しません。 this.contextは、ラップされたコンポーネントがHOCによってラップされている限り、空の{}です。助けてください?小道具として渡すことを伴わない文脈を伝える方法はありますか?

答えて

3

問題:contextTypesが定義されていない場合

、その後、コンテキストは空のオブジェクトになります。

ソリューション:

設定 HOC内部WrappedComponent.contextTypes

説明:未定着のコードで

SomeComponentためcontextTypesが設定されていません。 SomeComponent@withACoolThingで装飾された場合、SomeComponentに行った変更は、実際にはDoACoolThingに起こり、はSomeComponentに設定されないので、空のオブジェクト{}になります。

側注:

あなたはHOCでthis.contextを拡大し、ここで小道具としてそれを渡しているので:

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

あなたは、子コンポーネントで利用可能なthis.props.actions.doTheThingのようなものを持っている必要があります。

関連する問題