You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-native-web中自定义字体仅View生效、Text等组件不生效如何解决?

问题成因

React Native Web 为了保证和 React Native 端的表现一致,给 <Text>、<TextInput> 这类文本相关组件内置了默认的内联 font-family 样式,内联样式的 CSS 优先级远高于你写的全局 * 通配符选择器样式,所以全局字体设置会被覆盖。而 <View> 是容器组件,没有内置默认字体样式,所以你直接写在 <View> 里的裸文本可以正常继承全局字体,包在文本组件内的内容就不生效。

解决方案

以下方案按推荐度排序:

  • 方案1:封装统一的公共文本组件(最推荐,跨端兼容最好)
    自定义全局通用的 MyText、MyTextInput 组件,统一设置字体样式,业务代码全部替换为自定义组件即可,示例代码:
// components/MyText.js
import { Text } from 'react-native';
export default function MyText(props) {
  return <Text {...props} style={[{fontFamily: 'Vazir'}, props.style]} />
}

// components/MyTextInput.js
import { TextInput } from 'react-native';
export default function MyTextInput(props) {
  return <TextInput {...props} style={[{fontFamily: 'Vazir'}, props.style]} />
}
  • 方案2:通过CSS选择器命中RNW文本组件,提升优先级
    修改你 _document.js 里的全局CSS,专门匹配RNW渲染出来的文本元素,优先级足够覆盖内置样式,同时补全字体声明属性避免识别出错:
const normalizeNextElements = `
  #__next {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  @font-face {
    font-family : 'Vazir';
    src: url("/Vazir-Regular.woff2");
    font-weight: 400;
    font-style: normal;
  }
  * {
    font-family : 'Vazir';
  }
  /* 新增匹配RNW文本组件的样式 */
  [data-rnwelement="Text"], [data-rnwelement="TextInput"] {
    font-family: 'Vazir' !important;
  }
`
  • 方案3:临时快速修复
    仅用于测试场景,不推荐长期使用,可能会影响第三方组件样式表现:
* {
  font-family : 'Vazir' !important;
}

内容的提问来源于stack exchange,提问作者Mohammad Hekmati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:45:02