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