創建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