【问题标题】:How can you pass styles through to a container component in React-Native如何将样式传递给 React-Native 中的容器组件
【发布时间】:2016-08-05 04:07:53
【问题描述】:

我正在尝试为我的 React-Native 应用程序创建一些具有默认样式的可重用 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>
...

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

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我在浏览 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>
        }
    }
    

    【讨论】:

      【解决方案2】:

      使用打字稿和功能组件:

      type CustomProps = {
         text: string,
         onPress: () => void,
         style?: {}
      };
      
       const CustomButton = ({ style, text, onPress }: CustomProps) => {
         return (
          <TouchableOpacity
              style={[styles.container, style]}
              onPress={onPress}>
      
              <Text style={styles.text}>{text}</Text>
          </TouchableOpacity>
      )
      };
      
       const styles = StyleSheet.create({
           container: {
               elevation: 8,
               backgroundColor: Colors.white,
           },
           text: {
               fontSize: 18,
               color: Colors.primary_dark,
               fontWeight: "bold",
               alignSelf: "center",
               textTransform: "uppercase",
               textAlign: "center"
           }
       });
      

      然后像这样使用它:

      <CustomButton style={{ backgroundColor: 'red'}} text="hi" onPress={() => {console.log('Hi'}}
      

      【讨论】:

        猜你喜欢
        • 2018-05-13
        • 2016-12-24
        • 2017-12-02
        • 2019-01-18
        • 2019-06-26
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 2016-10-13
        相关资源
        最近更新 更多