我正在try 为我的React原生应用程序创建一些具有默认样式的可重用UI组件.

默认值为MyText(橙色,14,粗体)的示例:

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>
...

有办法做到这一点吗?显然,如果我try 访问this.props.style,它只会返回一个已编译样式表的ID.

推荐答案

我在浏览React Native Router Flux的源代码时找到了一种方法.

样式表可以作为数组传递,React Native似乎从左到右依次应用它们(允许覆盖特定属性).

以下是更新后的MyText组件的外观:

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相关问答推荐

单击react 本机时如何从同一屏幕更改内容

RNMK - 超级表达式必须为空或函数

react平面列表渲染项

在react-native 应用程序中使用中继

使用 React-Native 将 content:// URI 转换为 Android 的实际路径

如何在 React Native 中获取 TextInput 相对于其父级或屏幕的光标位置

redux-observable Promise 在单元测试中没有得到解决

如何判断 React Native 中的 AsyncStorage 中是否存在密钥? getItem() 总是返回一个promise对象

无法解析模块 react/lib/ReactUpdates

Typescript:onPress 类型

自定义原生基础的选项卡

react-native run-android 在设备上构建旧版本的代码

大型列表的 React-Native FlatList 性能问题

React-native Awesome 元素没有构建 android 元素

如何使用 Jest 测试导入自定义原生模块的 React Native 组件?

React-native iOS 不显示图像(pod 问题)

加载字体native-base 错误

React Native + Redux 基本认证

React 在任何根目录中都找不到入口文件

zIndex 不适用于react-native元素