React Native fontWeight 在 iOS 中不起作用

Sat*_*ill 4 react-native

我在 React Native 应用程序中使用了一个简单的文本组件。那么 fontWeight(仅粗体)仅不适用于 iOS。我已经在项目中插入了所有需要的字体(所有字体都在 Android 上运行良好)。

这是我的项目设置。

根/react-native.config.js

module.exports = {
  project: {
    ios: {},
    android: {},
  },
  assets:['/src/assets/fonts/']
}
Run Code Online (Sandbox Code Playgroud)

包.json

{
  "name": "boldfont",
  "version": "0.0.1",
  "private": true,
  "rnpm": {
    "assets": [
      "./src/assets/fonts"
    ]
  },
...  ...  ...
}
Run Code Online (Sandbox Code Playgroud)

根/src/资产/字体/ 在此输入图像描述

我也将所有这些字体添加到 android/app/src/main/assets/fonts 中。

That is my code.
Run Code Online (Sandbox Code Playgroud)

文本.js

import React from 'react';
import styled from 'styled-components/native';

function Stext({ ...props }) {
    return <Text {...props}>{props.children}</Text>
}

const Text = styled.Text`
    ${({ title, medium, small }) => {
        switch (true) {
            case title:
                return 'font-size: 48px;'
            case medium:
                return 'font-size: 20px;'
            case small:
                return 'font-size: 12px;'
            default:
                return 'font-size: 14px;'
        }
    }};

    ${({ PopBold, PopSemi, PopMedium }) => {
        switch (true) {
            case PopBold:
                return 'fontFamily: Poppins-Bold'
            case PopSemi:
                return 'fontFamily: Poppins-SemiBold'
            case PopMedium:
                return 'fontFamily: Poppins-Medium'
            default:
                return 'fontFamily: Poppins-Regular'
        }
    }}
`

export default Stext;
Run Code Online (Sandbox Code Playgroud)

主屏.js

import React from 'react'
import { View } from 'react-native'
import Stext from '../components/Stext'

export default function HomeScreen() {
  return (
    <View>
      <Stext PopBold>Android only</Stext>      // iOS not working
      <Stext PopSemi>Android and iOS</Stext>
      <Stext PopMedium>Android and iOS</Stext>
      <Stext>Android and iOS</Stext>
    </View>
  )
}
Run Code Online (Sandbox Code Playgroud)

Guy*_*Guy 7

在 iOS 中,你必须使用姓氏,例如{fontFamily: 'Poppins', fontWeight: 'bold'}

而在 Android 中,您必须包含包含所有不同变体的全名,就像{fontFamily: 'Poppins-Bold'}不需要传递 fontWeight 一样。

我知道这很烦人,您可以使用以下方法解决它Platform.select(...

这是一个示例代码:

const type = (family: string = "Poppins") => {
 return {
   semiBold: {
      fontFamily: Platform.select({ ios: family, android: `${family}-SemiBold` }), 
      fontWeight: Platform.select({ ios: "600" })
 },
   bold: {
      fontFamily: Platform.select({ ios: family, android: `${family}-Bold` }), 
      fontWeight: Platform.select({ ios: "700" })
 },
 }
}
Run Code Online (Sandbox Code Playgroud)

还有一个有用的跨平台实用程序库,您可以使用https://github.com/lendup/react-native-cross-platform-text