ReactNative进阶(四十六):移动端实现字体自适应

x33g5p2x  于2021-11-11 转载在 React  
字(4.1k)|赞(0)|评价(0)|浏览(394)

一、前言

在开发react-native App时,相信大家都遇到过这样的问题:当用户设置了系统的字体大小之后,导致APP布局紊乱,甚至有些内容会被切掉/隐藏,这对于用户来讲,是非常不好的用户体验。

那为什么会出现这种情况呢?原因是我们在开发的时候,布局的前提是系统的字体大小设置为默认大小,所以只能保证在系统字体大小正常的情况下,我们的布局是友好的,

那么,我们应该如何解决这个问题呢?今天这篇文章,就给大家介绍几种解决方案。

二、Text 和 TextInput

react-native中用来显示文字的,一般会用到两个组件:TextTextInput。所以,我们只要针对这两个组件做好工作,那就基本上解决了应用字体大小适配的问题。

TextTextInput它们有一个共同属性:allowFontScaling

该属性在react-native官方文档中解释如下:
Specifies whether fonts should scale to respect Text Size accessibility settings. The default is true.

翻译为:

应用字体是否随系统指定的文字大小变化而变化。默认值为true

这给我们提供了解决方案,只要给TextTextInput的属性allowFontScaling设置值为false,那么文字大小就不会随系统字体大小的变化而变化。

三、设置 allowFontScaling

有几种方式来设置TextTextInputallowFontScaling

3.1 Text 和 TextInput 组件设置 allowFontScaling = false

<Text allowFontScaling={false}/>
<TextInput allowFontScaling={false}/>

这种方案效率很低,需要在每个使用到这两个组件的地方都加上这个属性,考虑到这两个组件的使用率还是很高的,所以这是一个庞大的工作量,而且在开发过程当中,我们也很容易忘记设置它。

那么有没有更好实现方式呢?当然有,这就是下面讲的第二种:

3.2 自定义 MyText/MyTextInput 组件

可以自定义一个组件MyText, 然后统一设置allowFontScaling = false属性,然后在其他需要调用的时候,直接用MyText代替Text

MyText.js

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

export default class MyText extends React.Component {

    render() {
        return (
            <Text
                allowFontScaling={false}
                {...this.props}>
                {this.props.children}
            </Text>
        )
    }
}

这个方案足够好了,但是,你仍然可能在某段代码里,忘记使用MyText而是直接使用Text,这个时候,问题依然会出现。

那么,就没有一种万无一失的方案吗?当然有啦,第三种:

3.3 重写 Text 的 render()

可以重写Textrender()方法,让Text在渲染的时候,设置allowFontScaling = false。这里,需要用到lodashwrap()方法:

0.56(不包括)版本之前

Text.prototype.render = _.wrap(Text.prototype.render, function (func, ...args) {
    let originText = func.apply(this, args)
    return React.cloneElement(originText, {allowFontScaling: false})
})

注意1:
react-native版本0.56之前,Text是通过ReactcreateReactClass方式创建类的,也就是说,是通过javascriptprototype方式来创建类。所以重写render方法时,需要通过Text.prototype.render来引用。

而在0.56版本,Text改为了es6extends的实现方式来创建类,所以,需要如下方式来重写render

0.56(包括)版本之后

Text.render = _.wrap(Text.render, function (func, ...args) {
    let originText = func.apply(this, args)
    return React.cloneElement(originText, {allowFontScaling: false})
})
//设置ios字体大小不随系统的字体大小改变
const TextInputRender = TextInput.render;
TextInput.render = function (...args) {
  const originText = TextInputRender.apply(this, args);
  return React.cloneElement(originText, {
    allowFontScaling: Platform.OS === 'android', // 只在iOS平台设置为false
  });
};

const TextRender = Text.render;
Text.render = function (...args) {
  const originText = TextRender.apply(this, args);
  return React.cloneElement(originText, {
    allowFontScaling: Platform.OS === 'android', // 只在iOS平台设置为false
  });
};

大家可以查看源码,或者查看0.56的change-log

注意2:
这段代码最好放在app整个组件执行调用之前,比如在我的项目中:

import React from 'react'
import {AppRegistry, Text, DeviceEventEmitter, YellowBox} from 'react-native'
import {Provider} from 'react-redux'
import App from './src/App'
import _ from 'lodash'

//字体不随系统字体变化
Text.render = _.wrap(Text.render, function (func, ...args) {
    let originText = func.apply(this, args)
    return React.cloneElement(originText, {allowFontScaling: false})
})

...
...

class MyApp extends React.Component {
    render() {
        return (
            <Provider store={store}>
                <App/>
            </Provider>
        )
    }
}

AppRegistry.registerComponent("xxx", () => MyApp);

注意3:
但是很遗憾的是,这个只适用于TextTextInput不能用于此方案。

那么,有没有一种方案,能够同时兼容TextTextInput并且做到一劳永逸呢?当然有了,终极方案:

3.4 完美方案:修改 defaultProps

首先我们来看各种组件的源码.

TextInput.js

...
  getDefaultProps(): Object {
    return {
      allowFontScaling: true,
      underlineColorAndroid: 'transparent',
    };
  },
...

Text.js

...
  static defaultProps = {
    accessible: true,
    allowFontScaling: true,
    ellipsizeMode: 'tail',
  };
...

通过这两个代码片段可以知道,在定义TextTextInput时,都有给组件设置默认属性的操作.

所以,可以通过:

TextInput.defaultProps = Object.assign(
    {}, TextInput.defaultProps, {defaultProps: false})
    
Text.defaultProps = Object.assign(
    {}, Text.defaultProps, {allowFontScaling: false})

来直接设置TextTextInputallowFontScaling属性默认值为false,真正实现了一劳永逸。

四、确保 react-navigation 兼容

通过设置defaultProps的方式来修改allowFontScaling的值为false,会有一个问题。

大家在使用react-native时,最常用到的navigator应该是react-navigation。你需要单独设置headertitleallowfontscalingallowFontScaling来确保react-navigationtabTitleheaderTitle没有问题。

五、总结

  • react-native中使用TextTextInput负责显示文字信息;
  • TextTextInput中设置allowFontScaling=false可以让字体大小不随系统设置而变化;
  • 可以通过单个组件设置、自定义组件、重写render()、设置defaultProps默认值这四种方式来设置allowFontScaling的值为false
  • 对于重写render()、设置defaultProps默认值这两种方式,需要把设置代码放在app组件初始化之前。
  • 确保react-navigation兼容。

六、拓展阅读

相关文章