将原生应用样式应用于所有文本组件

时间:2016-12-10 16:08:56

标签: react-native

是否有一种简单的方法可以将样式应用于特定类型的所有组件,例如TextScrollView等,以构建模板的原生作用?
例如,我希望将verdana fontFamily样式用于所有场景中的所有Text组件。有没有一种简单的方法来实现,而不是每次使用Text组件时指定样式?
或者是否需要创建自定义文本组件?并使用它代替基本组件,如下面的例子。使用MyText代替Text

const MyText = ({data}) => <Text style={style.commonTextStyle}>{data}</Text>

7 个答案:

答案 0 :(得分:7)

除了Vicky的答案,您只需创建一个名为Text或MyText等的新组件,并在需要时将其导入您的项目。

function MyText(props) {
  return (
    <Text style={styles.MY_CUSTOM_STYLES}>
      {props.children}
    </Text>
  );
}

并使用它,

import MyText from '/path/to/MyText';

...

render() {
  return ( <MyText>Now I have my custom styles.</MyText> );
}

如果您习惯于定义Text组件,可以通过更改其名称将其用作导入文本。有关详细信息,请参阅this documentation(请注意:上面的MyText组件是轻量级定义的functional stateless component。)

答案 1 :(得分:3)

您必须创建一个这样的RN组件:

/* @flow */

import React, { Component } from 'react';
import { Text as TextRN } from 'react-native';

export default class Text extends Component {
  render() {
    return (
      <TextRN style={[YOUR_CUSTOM_STYLES, this.props.style]}>
        {this.props.children}
      </TextRN>
    )
  }
}

通过这种方式,您自己的Text组件可以在您使用它们的任何地方继承其他样式。

注意:请注意,您自己的自定义文本组件不能在所有情况下使用,例如在TouchableHighlight中,在这种情况下,您必须使用react-native库中的本机文本。

现在,您只需更改导入:

import Text from 'YOUR_PATH/Text.js'

希望这有帮助。

答案 2 :(得分:2)

您可以提取常见样式并将其作为全局样式提供。如果需要,您可以为每个文本视图添加/编辑样式。

export default StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
})

然后你可以使用<Text style={[styles.welcome, {color:'red'}]]}>Hello</Text>

你应该查看像react-native-extended-stylesheet

这样的库

您还可以按照这些技巧了解如何保持样式表简单易读 请参阅Tips for styling React

答案 3 :(得分:1)

您可以创建一个新组件并在其中应用所需的任何修改。

class MyText extends Component {
    render() {
        return <Text {...this.props}
                     style={[this.props.style, style.commonTextStyle]}>{this.props.children}</Text>;
    }
}

别忘了添加{... this.props}。这样,您就可以将所有道具传递给您要定义的新组件。

答案 4 :(得分:1)

在您的 Global-Styles js文件中:

import React from "react";
import {
  Text as RNText
} from "react-native";

const styles = {
  text: {
    lineHeight: "1.5em",
    fontSize: "1.125rem",
    marginVertical: "0.2em",
    textAlign: "center"
  }
}

export var Text = (props) => <RNText style={[styles.text, props.style]}>{props.children}</RNText>

用法(与普通文本相同)

import {Text} from './StyledComponents'

...
<Text style={{marginTop: '20px', color: 'red'}}>Hello, World!</Text>

答案 5 :(得分:0)

https://github.com/Ajackster/react-native-global-props似乎为大多数反应原生组件提供全局样式,包括Text,View等。来自GitHub的自述文件有示例。这似乎解决了这个问题,但我还没有测试过。

答案 6 :(得分:0)

Glamorous在React Native中也非常干净地处理这个问题:

const MyText = glamorous.Text({
  // ... any styles
});

export MyText;
相关问题