我认为解析返回的元素是错误的方法 . 一个挑战是 style 的值将是一个对象( styles.container ===样式键/值的散列),而您需要一个可以映射到对象的键 .
我认为最可重用的方法是利用React上下文(我假设RN支持!)来构建一个 styleName ,它可以在你下载组件树时进行扩充 .
这是一个初始方法,它做了一些假设(例如,每个组件都将 styleName 作为prop提供;您可能希望在设计时而不是运行时提供它) . 简而言之,您使用此HOC包装要参与的每个组件,并将 styleName 作为每个组件的prop . 连接这些 styleName 值以生成映射到样式的上下文化名称 .
这个例子产生:
const CascadingStyle = (styles, Wrapped) => class extends React.Component {
static displayName = 'CascadingStyle';
static contextTypes = {
styleName: React.PropTypes.string
}
static childContextTypes = {
styleName: React.PropTypes.string
}
// pass the current styleName down the component tree
// to other instances of CascadingStyle
getChildContext () {
return {
styleName: this.getStyleName()
};
}
// generate the current style name by either using the
// value from context, joining the context value with
// the current value, or using the current value (in
// that order).
getStyleName () {
const {styleName: contextStyleName} = this.context;
const {styleName: propsStyleName} = this.props;
let styleName = contextStyleName;
if (propsStyleName && contextStyleName) {
styleName = `${contextStyleName}_${propsStyleName}`;
} else if (propsStyleName) {
styleName = propsStyleName;
}
return styleName;
}
// if the component has styleName, find that style object and merge it with other run-time styles
getStyle () {
if (this.props.styleName) {
return Object.assign({}, styles[this.getStyleName()], this.props.styles);
}
return this.props.styles;
}
render () {
return (
);
}
};
const myStyles = {
container: {backgroundColor: 'green', color: 'red'},
container_text: {color: 'blue'}
};
const Container = CascadingStyle(myStyles, (props) => {
return (
);
});
const Text = CascadingStyle(myStyles, (props) => {
return (
);
});
const Component = () => {
return (
Some Text
);
};