javascript - 如何创建自定义文本 - React Native

标签 javascript react-native

我现在完成了我的项目,我想将我的自定义字体设置为所有 Text 组件。

我认为最好的方法是创建一个自定义的 Text 组件并将其替换为 react-native 的默认 Text。

现在如何创建具有默认样式的自定义 Text 组件?

最佳答案

为此,您需要有一个 React 原生组件,该组件在实例化后可通过样式或其他属性进行配置。

例如,您可以像这样让您的自定义 React native 组件 CustomText:

<强>1。功能组件

如果你更喜欢新的方式并且你将使用它与钩子(Hook),使用这个部分:

// CustomText.js    
import React from 'react';
import {
  Text,
  StyleSheet,
} from 'react-native';

export default function CustomText(props) {
  return (
    <Text style={[styles.defaultStyle, props.style]}>
      {props.children}
    </Text>
  );
}

const styles = StyleSheet.create({
  // ... add your default style here
  defaultStyle: {
  },
});

<强>2。类组件

如果您更喜欢使用类的旧方法,请使用此部分:

// CustomText.js    
import React from 'react';
import {
  Text,
  StyleSheet,
} from 'react-native';

export default class CustomText extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Text style={[styles.defaultStyle, this.props.style]}>
        {this.props.children}
      </Text>
    );
  }
}

const styles = StyleSheet.create({
  // ... add your default style here
  defaultStyle: {
  },
});

然后在您的主要组件上导入并调用该自定义组件,如下所示:

import CustomText from './CustomText';
//... other imports go here.

// in the render method you call your CustomText component.
render(){

//...
  <CustomText style={{ fontWeight: 60, }}>
    This is custom Text
  </CustomText>
}

注意:如果您只想更改样式,我认为 @Yanush 解决方案最适合这种情况。

希望对您有所帮助。

关于javascript - 如何创建自定义文本 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262325/

相关文章:

javascript - 如何动态使用字符串值作为返回对象中的键类型以获得正确的类型?

javascript - jquery .on click 不适用于后来添加的元素

React-Native:如何制作图像数组

javascript - React native Android 给出关于 gradle 的错误

javascript - 设置状态后无法编辑 inputText [react-native]

react-native - 使用 React Native 和 Tensorflow.js 对实时视频进行预测

javascript - 如何调试我的轮盘 JavaScript 程序?

javascript - 如何动态删除 jquery 脚本中的空格和新行?

javascript - 将新状态设置为现有数组状态

react-native - 安装或运行应用程序时出错