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

问题描述 投票:0回答:2

我有一个<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',
}

textAlign内的textWithInContainer未被适用。如果我将textAlign: 'center'添加到styles.text给我我想要的风格,但它在不同的屏幕中使用,我只希望它在screenFile中心。我希望styles.textWithinContainer的样式覆盖styles.text中的样式。我该怎么做?

javascript reactjs react-native
2个回答
6
投票

您没有将传递给TextFile的样式委托给Text中的实际TextFile元素。你可以做的是通过传递样式对象数组来将样式添加到一起来应用它:

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

来自the React Native documentation

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

因此,如果你在textAlign中传递textWithContainer,它将被应用在Text组件中,并且可以在没有textAlign的情况下重复使用。


0
投票

在我最初的TextFile中,我将style作为参数传递,并且在styles数组中,仅使用style作为数组中的第二项。

const TextFile = ({ text, style }) => (
   <Text style=([styles.text, style])> {text} </Text>
);

每当使用TextFile时,它将应用在该组件中给出的任何样式,和/或默认为它在styles.text中给出的初始样式。

谢谢@Li357!

© www.soinside.com 2019 - 2024. All rights reserved.