关于上下文的this article之后,我们使用辅助方法 withContext (下面的定义)来浏览与主题相关的信息。
这适用于组件(上下文作为props传递):
export const Empty = (props) => <View>
<Text>{props.children}</Text>
</View>;
export default withContext(Empty);
但是,我们更喜欢调用使用组件的withContext而不是定义:
import {withContext} from "./utils/context";
import Empty from "./layout_modules/empty/Empty";
Empty = withContext(Empty);
问题是 import statements 可能会被转换为const导致此错误:
“Empty”是只读错误。
使用require工作但很复杂:
const Empty = withContext(require("./layout_modules/empty/Empty").Empty);
使用import并调用withContext的任何优雅方式?
方法的定义:
const allTypes = {
locale: PropTypes.string,
colors: PropTypes.object,
i18n: PropTypes.object,
fontFamily: PropTypes.object,
};
const consumeContext = (contextTypes) => (Component) => {
const ContextConsumer = (props, context) =>
<Component {...props} {...context} />;
ContextConsumer.contextTypes = contextTypes;
return ContextConsumer;
};
export const withContext = (Component) => {
return consumeContext(allTypes)(Component);
}