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

如何阻止Prettier在JSX标签间自动添加{" "}字符?

解决Prettier给React Native JSX自动添加{" "}的问题

问题说明

使用Prettier格式化React Native的JSX代码时,工具会自动在<View>与<StatusBar>标签之间插入{" "}字符,需要彻底禁用该行为。

原代码:

export default function App() {
  return (
    <View className="h-full flex flex-row justify-center bg-blue-500">
<View className="h-fit">
        <Text className="bg-red-500">THIS WILL BE CENTERED</Text>
  
</View>      <StatusBar style="auto" />
    </View>
  );
}

格式化后代码:

export default function App() {
  return (
    <View className="h-full flex flex-row justify-center bg-blue-500">
      <View className="h-fit">
        <Text className="bg-red-500">THIS WILL BE CENTERED</Text>
      </View>{" "}
      <StatusBar style="auto" />
    </View>
  );
}

解决方法

  • 修改全局Prettier配置:在项目的.prettierrc或.prettierrc.js配置文件中,添加或调整以下规则:

    {
      "htmlWhitespaceSensitivity": "ignore",
      "jsx-preserve-newlines": false,
      "jsx-bracket-same-line": true
    }
    

    其中htmlWhitespaceSensitivity设为ignore会让Prettier忽略JSX的空格敏感性,不再刻意保留空格;jsx-preserve-newlines关闭后,工具不会在标签间强制补空格。

  • 局部禁用格式化:如果只想针对特定位置禁用,在标签之间添加{/* prettier-ignore */}注释即可:

    <View className="h-fit">
      <Text className="bg-red-500">THIS WILL BE CENTERED</Text>
    </View>{/* prettier-ignore */}
    <StatusBar style="auto" />
    
  • 升级Prettier版本:部分旧版本Prettier对React Native的JSX处理存在bug,升级到最新稳定版(如3.x系列)可自动修复该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:42:36