有没有一种方法可以通过 React 高阶组件将上下文传递给它包装的组件?
我有一个 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;
传递{...this.context}
HOC 不起作用。只要被包裹的组件被 HOC 包裹,它this.context
就是空的。{}
请帮忙?有什么方法可以传递不涉及将其作为道具传递的上下文?