【问题标题】:Passing Styles Based on Parent Component in React NativeReact Native 中基于父组件传递样式
【发布时间】:2017-12-15 16:20:31
【问题描述】:

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

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

【问题讨论】:

  • TextFile 正在返回一个 Text 元素。 textWithinContainerView 中的Text 元素
  • 哦,对了。

标签: javascript reactjs react-native


【解决方案1】:

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

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

来自the React Native documentation

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

因此,如果您在textWithContainer 中传递textAlign,它将被应用到Text 组件中,并且可以根据需要重复使用它 textAlign。 p>

【讨论】:

  • 当我使用this.props.style 时,我得到了一个TypeError: Cannot read property 'style' of undefined。然后我在TextFile 中尝试了{[styles.text, styles.textWithinContainer]},正如预期的那样,textWithinContainer 样式被整体应用。在&lt;View&gt; 中,我是否将任何内容传递给样式? &lt;TextFile styles={styles.textWithinContainer} /&gt; ?
  • @Dres 你用的是函数组件吗?在这种情况下,请使用props.style
  • 我是。 const TextFile = ({ text }) =&gt; ( &lt;Text accessible={true} style={[styles.text, props.style]} numberOfLines={2} ellipsizeMode={'tail'} &gt; {text} &lt;/Text&gt; );props.style 给了我ReferenceError: props is not defined
  • @Dres 好的。 const TextFile = ({ style, text }) =&gt; &lt;Text style={[styles.text, style]}&gt;&lt;/Text&gt;
  • 没有错误,但样式也没有变化&lt;TextFile styles={styles.textWithinContainer}&gt;&lt;View&gt; 内。 ` 是我现在正在尝试的,但没有运气。顺便说一句,感谢您的帮助
【解决方案2】:

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

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

无论何时使用TextFile,它都会应用该组件中给出的任何样式,和/或默认为styles.text 中给出的初始样式。

谢谢@Li357!

【讨论】:

    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2019-07-13
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多