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

如何在VS Code中排序React组件属性?(已用ESLint和Prettier)

React组件属性排序方案(适配ESLint/Prettier工作流)

当然有方案,而且完全可以集成到你现有的VS Code+ESLint+Prettier工作流里,不用额外装独立插件:

  • 核心工具:ESLint的eslint-plugin-react插件
    这个插件自带的react/jsx-sort-props规则,支持按字母顺序、属性类型、自定义优先级等多种方式排序React组件属性。

    配置步骤:

    1. 确保已安装eslint-plugin-react(未安装则执行npm install eslint-plugin-react --save-dev)
    2. 在ESLint配置文件(如.eslintrc.js或.eslintrc.json)中添加规则:
      {
        "plugins": ["react"],
        "rules": {
          "react/jsx-sort-props": [
            "error",
            {
              "ignoreCase": true, // 忽略大小写排序
              "reservedFirst": true, // React内置属性(如alt、src)优先排列
              "callbacksLast": true, // 回调类属性(如onClick)放在最后
              "multiline": "last", // 多行属性时,最后一项单独换行
              "shorthandFirst": true // 扩展属性(如{...props})放在前面
            }
          ]
        }
      }
      
  • 和Prettier兼容
    为避免排序规则与Prettier格式化冲突,确保安装eslint-config-prettier,并在ESLint配置中加入extends数组:

    {
      "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "prettier"
      ]
    }
    
  • VS Code自动生效
    开启VS Code的ESLint自动修复(设置中开启editor.codeActionsOnSave.fixAll.eslint),保存文件时组件属性会自动按配置规则排序。

    你提供的代码按上述配置排序后会变成:

    <Image
      alt=""
      src="/img/logo.svg"
      height="30"
      width="30"
      className="d-inline-block align-top"
    />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:15:02