创建HOC是解决主题化的好办法。让我分享另一个想法,使用React的Context。
上下文允许您将数据从父节点传递到它的所有子节点。 通过在组件定义中定义contextTypes
,每个孩子可以选择访问context
。
比方说App.js是你的根。现在
import themingConfig from 'config/themes';
import i18nConfig from 'config/themes';
import ChildComponent from './ChildComponent';
import AnotherChild from './AnotherChild';
class App extends React.Component {
getChildContext() {
return {
theme: themingConfig,
i18n: i18nConfig, // I am just showing another common use case of context
}
}
render() {
return (
<View>
<ChildComponent />
<AnotherChild myText="hola world" />
</View>
);
}
}
App.childContextTypes = {
theme: React.PropTypes.object,
i18n: React.PropTypes.object
};
export default App;
我们`ChildComponent.js谁想要一些主题和国际化的字符串
class ChildComponent extends React.Component {
render() {
const { i18n, theme } = this.context;
return (
<View style={theme.textBox}>
<Text style={theme.baseText}>
{i18n.someText}
</Text>
</View>
);
}
}
ChildComponent.contextTypes = {
theme: React.PropTypes.object,
i18n: React.PropTypes.object
};
export default ChildComponent;
AnotherChild.js谁只想主题,但没有国际化。他可能是无状态的,以及:
const AnotherChild = (props, context) {
const { theme } = this.context;
return (<Text style={theme.baseText}>{props.myText}</Text>);
}
AnotherChild.propTypes = {
myText: React.PropTypes.string
};
AnotherChild.contextTypes = {
theme: React.PropTypes.object
};
export default AnotherChild;
我试图使用'withTheme'像这样的功能组件: – aminimalanimal
'出口常量圈= withTheme(({}题材)=>(<圈填充= {主题.circleColor} r =“40”/>))' – aminimalanimal
虽然我得到一个错误,说它没有返回一个React节点,所以我假设'withProps'目前不能用于功能组件? – aminimalanimal