如何将样式传递给 React-Native 中的容器组件 [英] How can you pass styles through to a container component in React-Native
问题描述
我正在尝试为具有默认样式的 React-Native 应用程序创建一些可重用的 UI 组件.
I'm trying to create some reusable UI components for my React-Native app that have default styles.
示例默认 MyText
(橙色、14、粗体):
An example default MyText
(orange, 14, bold):
import React, { Component, StyleSheet, Text } from 'react-native';
const styles = StyleSheet.create({text: {color: 'orange', fontSize: 14, fontWeight: 'bold'}});
export default class MyText extends Component {
render() {
return <Text style={styles.text}>{this.props.children}</Text>
}
}
我想如何使用它:
import Text from '../ui/myText';
...
<Text style={{color: 'black'}}>My custom styled text, but in black instead of orange</Text>
...
有没有办法做到这一点?显然,如果我尝试访问 this.props.style
它只会返回一个已编译样式表的 ID.
Is there a way to do this? Obviously if I try to access this.props.style
it just returns an ID for a compiled stylesheet.
推荐答案
我在浏览 React-Native-Router-Flux 的源代码时找到了一种方法.
I found a way to do it while browsing through the source code for React-Native-Router-Flux.
样式表可以作为数组传入,看起来 React-Native 是按照从左到右的顺序应用它们的(允许你覆盖特定的属性).
Stylesheets can be passed in as an array, and it looks like React-Native applies them in order from left to right (allowing you to overwrite specific properties).
更新后的 MyText
组件如下所示:
Here is what the updated MyText
component should look like:
import React, { Component, StyleSheet, Text } from 'react-native';
const styles = StyleSheet.create({text: {color: 'orange', fontSize: 14, fontWeight: 'bold'}});
export default class MyText extends Component {
render() {
return <Text style={[styles.text, this.props.style]}>{this.props.children}</Text>
}
}
这篇关于如何将样式传递给 React-Native 中的容器组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!