[英]React-native style to text elements
我已经像这样定义了JSX
<View style={[color: 'red']}>
<Text>Text1</Text>
<Text>Text2</Text>
<Text>Text3</Text>
</View>
视图组件没有颜色属性,也不应用子元素的文本颜色设置。
我不想在单个元素上应用相同的样式。 如何在父级上定义样式并应用于HTML中的所有子元素?
样式正在Text
组件之间传播,因此您可以执行以下操作:
<Text style={{color: 'red'}}>
<Text>Text1</Text>
<Text>Text2</Text>
<Text>Text3</Text>
</Text>
除了单独为每个元素应用样式之外,您可以使用类似于lodash _.map
并以编程方式呈现每个子项并声明样式一次。
您是否尝试这样做是因为您希望每个文本标签都有不同的颜色?
为了减少代码,你也可以“解构”它。
const { aStyle, anotherStyle, andAnotherStyle } = styles;
而不是styles.aStyle. styles.anotherStyle...
styles.aStyle. styles.anotherStyle...
据我所知,没有简单的方法可以从超级Componnet继承样式。
也许你可以自定义这样的组件:
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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.