我这样定义了JSX
<View style={[color: 'red']}>
<Text>Text1</Text>
<Text>Text2</Text>
<Text>Text3</Text>
</View>
视图组件没有color属性,并且它不应用子元素的文本颜色设置。
我不想在单个元素上应用相同的样式。如何定义父元素上的样式,并像HTML中的normal那样应用于所有子元素?
发布于 2016-08-10 09:09:02
该样式在Text
组件之间传播,因此您可以执行以下操作:
<Text style={{color: 'red'}}>
<Text>Text1</Text>
<Text>Text2</Text>
<Text>Text3</Text>
</Text>
发布于 2016-08-10 08:15:14
据我所知,没有一种简单的方法可以从超级组件网上继承样式。
也许你可以像这样自定义一个组件:
class YourComponent extends Component {
render() {
let children = [];
React.Children.forEach(this.props.children, (item, index) => {
// textStyle is the style that you want children to inherit
children.push(React.cloneElement(item, this.props.textStyle));
});
return (
<View>
{ children }
</View>
);
}
}
发布于 2017-03-12 00:24:21
除了将样式单独应用于每个元素之外,您还可以使用类似lodash的_.map
,并以编程方式呈现每个子元素,然后声明一次样式。
你尝试这样做是因为你想在每个文本标签上使用不同的颜色吗?
为了减少代码,你也可以“解构”它。
const { aStyle, anotherStyle, andAnotherStyle } = styles;
而不是styles.aStyle. styles.anotherStyle...
。
https://stackoverflow.com/questions/38866745
复制