代码之家  ›  专栏  ›  技术社区  ›  Get Off My Lawn

如何让eslint选择具有特定类的className的jsx元素?

  •  0
  • Get Off My Lawn  · 技术社区  · 2 月前

    我正在实现eslint,并且我正在使用 'no-restricted-syntax' 要创建自定义选择,我的选择如下:

      'no-restricted-syntax': [
        'error',
        {
          selector: 'JSXElement JSXAttribute JSXIdentifier[name="className"] + Literal[value="bg-red"]',
          message: 'Do not set background colors directly.',
        },
      ],
    

    我正在这个测试组件上测试代码,但没有发现错误:

    export function TestComponent() {
      return <button className="bg-red">Click me</button>;
    }
    

    我也曾尝试将选择器修改为以下内容,但未能成功:

    // On the attribute
    JSXElement JSXAttribute[name="className"][value="bg-red"]
    
    // removing the + Literal
    JSXElement JSXAttribute JSXIdentifier[name="className"][value="bg-red"]
    

    如何让eslint选择具有 className 包含一个特定的类(或者更好的是一个以以下开头的类 bg )?

    如果它有帮助,这里是 ESLint explorer

    1 回复  |  直到 2 月前
        1
  •  2
  •   Abraham tim    2 月前

    查看json中给定的[ESLint explorer][1],

    选择器应该是 JSXAttribute[name.name="className"][value.value 而不是 JSXAttribute[name="className"][value=

    {
      "name": {
        "type": "JSXIdentifier",
        "start": 46,
        "end": 55,
        "name": "className"
      },
      "value": {
        "type": "Literal",
        "start": 56,
        "end": 64,
        "value": "bg-red",
        "raw": "\"bg-red\""
      }
    }