【问题标题】:React Native 0.18.1 use custom font on all viewsReact Native 0.18.1 在所有视图上使用自定义字体
【发布时间】:2016-05-03 07:27:46
【问题描述】:

我刚刚升级到 RN 0.18.1,以前在我的应用程序中使用自定义字体的方式不再有效。有什么解决方法吗?

我曾经这样做过:

import React, {AppRegistry, Component, StyleSheet, Text, View, TextInput} from 'react-native';

var OldText = Text;

class NewText extends OldText {
  defaultProps = {
    customFont: false
  };

  render() {
    var props = _.clone(this.props);

    if (this.props.customFont) {
      return super.render();
    }

    if (_.isArray(this.props.style)){
      props.style.push({fontFamily: 'Quicksand-Regular'});
    } else if (props.style) {
      props.style = [props.style, {fontFamily: 'Quicksand-Regular'}];
    } else {
      props.style = {fontFamily: 'Quicksand-Regular'};
    }

    this.props = props;

    return super.render();
  }
};

React.Text = NewText;

现在在最后一行 React.Text = NewText 上,我收到错误:“尝试分配给只读属性”。现在有关于如何使用自定义字体的想法吗?

【问题讨论】:

  • 您可以导出 NewText 并在整个渲染方法中使用 而不是 ,但这并不像您所做的那样简洁。
  • 是的,这就是我的想法,但我想知道是否还有其他方式更“清洁”。我认为这样做的方法是将字体添加到每个 Text 标签的样式中,但这需要一些时间。
  • “可重用组件”文档建议子类化来实现这一点,即始终使用 组件。我为应用程序中使用的每种字体样式(TextHeader、TextInfo 等)制作了文本组件
  • 好的,谢谢本克莱顿。那我就做吧。

标签: javascript fonts react-native


【解决方案1】:

感谢@Ben Clayton 的回答。 现在正确的做法是创建一个新组件(NewText),例如,它是 React.Text 的子类,并在整个应用程序中使用它而不是使用它。

我的 NewText 看起来像这样:

'use strict';

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

import _ from 'lodash';

class NewText extends Text {
  defaultProps = {
    customFont: false
  };

  render() {
    var props = _.clone(this.props);

    if (this.props.customFont) {
      return super.render();
    }

    if (_.isArray(this.props.style)){
      props.style.push({fontFamily: 'Quicksand-Regular'});
    } else if (props.style) {
      props.style = [props.style, {fontFamily: 'Quicksand-Regular'}];
    } else {
      props.style = {fontFamily: 'Quicksand-Regular'};
    }

    this.props = props;

    return super.render();
  }
};

export default NewText;

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多