react native 处理iOS和安卓系统文字

553 阅读1分钟

非常简单的几步 让 react native app不随系统文字变化的处理

ios 处理方法如下 :

  1. 新增addCustomProps.js (位置随意放到项目目录, 只要路径引用的到) 下面是 addCustomProps.js 的内容

/**
 * 添加组件的的自定义属性
 * @param WrapComponent 组件
 * @param customProps 默认属性
 */
export default function addCustomProps(WrapComponent, customProps) {
	const componentRender = WrapComponent.prototype.render
	const componentDefaultProps = WrapComponent.prototype.constructor.defaultProps
	WrapComponent.prototype.constructor.defaultProps = {
		...componentDefaultProps,
		...customProps
	}
	WrapComponent.prototype.render = function render() {
		const oldProps = this.props

		this.props = {
			...this.props,
			style: [customProps.style, oldProps.style]
		}
		return componentRender.apply(this)
	}
}
  1. 在你app的入口文件里加上如下内容 (⚠️注意 是入口文件 ,否则可能不起作用)
import React, { Component } from 'react'
import { Text, TextInput } from 'react-native'

// 处理iOS系统文字
addCustomProps(Text, {allowFontScaling: false});
addCustomProps(TextInput, {allowFontScaling: false});

ios 端完成, 你可以试着修改系统的文字大小实验

android 处理方法如下 :

在 MainApplication.java 文件中加入如下代码:

import android.content.res.Configuration;
import android.content.res.Resources;

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    if (newConfig.fontScale != 1) // 非默认值
      getResources();
    super.onConfigurationChanged(newConfig);
  }

  @Override
  public Resources getResources() {
    Resources res = super.getResources();
    if (res.getConfiguration().fontScale != 1) { // 非默认值
      Configuration newConfig = new Configuration();
      newConfig.setToDefaults(); // 设置默认
      res.updateConfiguration(newConfig, res.getDisplayMetrics());
    }
    return res;
  }

android 端也完成了