日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

React?Native?中處理?Android?手機(jī)吞字的解決方案_React

作者:todoit ? 更新時(shí)間: 2022-09-29 編程語(yǔ)言

React Native App 在部分型號(hào)的 Android 手機(jī)上,可能會(huì)發(fā)生文字顯示不全的問題。

官方也有一個(gè)?相關(guān)的 Issue?,并提供了如下的解決方案:

const defaultFontFamily = {
  ...Platform.select({
    android: { fontFamily: "" },
  }),
}

const oldRender = Text.render
Text.render = function (...args) {
  const origin = oldRender.call(this, ...args)
  return React.cloneElement(origin, {
    style: [defaultFontFamily, origin.props.style],
  })
}

但是升級(jí) React Native 到 0.66 之后,上面這個(gè)方法就不起作用了。

復(fù)現(xiàn)問題

作者在 React Native 0.67.4 環(huán)境下,編寫了一個(gè)小 demo 來復(fù)現(xiàn)這個(gè)問題,如下:

function IncompleteText() {
  return (
    <View style={styles.container}>
      <View style={styles.row}>
        <Text style={styles.text}>我在左邊 完整</Text>
        <Text style={styles.text}>我在右邊 完整</Text>
      </View>
      <View style={styles.row}>
        <Text style={styles.text}>12345</Text>
        <Text style={styles.text}>67890</Text>
      </View>
      <View style={styles.row}>
        <Text style={styles.text}>abcd</Text>
        <Text style={styles.text}>efgh</Text>
      </View>
      <View style={styles.row}>
        <Text style={styles.text}>今年是 2022 年</Text>
        <Text style={styles.text}>虧了好多 ¥</Text>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  row: {
    marginTop: 16,
    marginHorizontal: 24,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    height: 60,
    backgroundColor: "#f5f5f5",
  },
  text: {
    fontSize: 18,
    color: "#333333",
    fontWeight: "normal",
    // fontFamily: 'DFWaWaSC-W5',
    backgroundColor: "yellow",
  },
})

當(dāng)?Text?中的文本同時(shí)符合以下兩個(gè)條件時(shí),在部分 Android 手機(jī)上會(huì)出現(xiàn)文字顯示不全的問題。

fontWeight

譬如作者這臺(tái)手機(jī):

手機(jī)型號(hào) MIUI 版本 Android 版本
MI 8 12.5.2 10

就會(huì)出現(xiàn)文字顯示不全的問題,即使將?fontWeight?設(shè)置為?bold?,也不會(huì)有粗體效果。

但是只要 style 設(shè)置了?fontFamily?,就不會(huì)有顯示不全的問題,因此,怎樣才能正確地設(shè)置?fontFamily?呢?

解決問題

stack overflow 上,有人問?How to set default font family in React Native??。

在該問題的討論列表中,作者找到了適合 React Native 0.66 以上版本的解決方案,如下:

// text-polyfill.ts
import React from "react"
import { Platform, StyleSheet, Text, TextProps } from "react-native"

const defaultFontFamily = {
  ...Platform.select({
    android: { fontFamily: "" },
  }),
}

// @ts-ignore
const __render: any = Text.render

// @ts-ignore
Text.render = function (props: TextProps, ref: React.RefObject<Text>) {
  if (Platform.OS === "ios") {
    return __render.call(this, props, ref)
  }

  const { style, ..._props } = props
  const _style = StyleSheet.flatten(style) || {}
  return __render.call(
    this,
    { ..._props, style: { ...defaultFontFamily, ..._style } },
    ref
  )
}

示例

這里有?一個(gè)示例?,供你參考。

原文鏈接:https://juejin.cn/post/7127811778620162078

欄目分類
最近更新