小编典典

在React Native中基于父组件传递样式

reactjs

我有一个<Text>正在传递样式的组件。

TextFile.js

<Text style={styles.text}> 
  This is a line of text and this might be a second line 
</Text>

screenFile.js

<View style={styles.viewContainer}>
    <TextFile style={styles.textWithinContainer}>
</View>

textFiles/styles.js

text: {
    fontSize: 20,
    color: 'black',
    fontWeight: '400',
}

screenFiles/styles.js

textWithinContainer: {
    textAlign: 'center',
}

textAligntextWithInContainer未应用。如果我添加textAlign: 'center'styles.text给我我想要的风格,但它在不同的屏幕上正在使用的,我只希望它处于中心screenFile。我希望from
styles.textWithinContainer中的样式覆盖中的样式styles.text。我将如何处理?


阅读 335

收藏
2020-07-22

共1个答案

小编典典

您无需将传递给样式的样式委派给TextFile中的实际Text元素TextFile。您可以做的是通过传递样式对象 数组 来将样式加在一起:

<Text style={[styles.text, props.style]}> 
  This is a line of text and this might be a second line 
</Text>

React Native文档中

您还可以传递样式数组-数组中的最后一个样式具有优先级,因此您可以使用它来继承样式。

因此,如果传递textAligntextWithContainer,它会在应用Text组件,并且你希望它可以重复使用 而不会
textAlign

2020-07-22