如何解决这种违反 eslint 规则的“反应/无逃逸实体”的情况?

这是我的暗号:

const func = () => {
return (
<div >
you're free
</div>
)}

以某种方式,eslint 用错误 error HTML entities must be escaped react/no-unescaped-entities标记行“ you’re free”

然而从我所看到的 jsx 已经避开了撇号。我可以看到字 you're free是没有问题的呈现。如果我以 &#39;的形式转义它,那么搜索字符串将会非常困难(我希望在编辑器中搜索 you're free会返回一个命中。但是显然编辑器会错过,因为文本实际上是 you&#39;re free)

那么,解决这个 eslint 异常的最佳方法是什么呢?

73505 次浏览

I explicitly escape the whole block of text by enclosing the line in {" "}:

const func = () => {
return (
<div >
{" you're free "}
</div>
)}

Recommended solution is to use &apos;, &lsquo; or &rsquo; instead of wrapping it as a variable. So like this:

const func = () => {
return (
<div >
you&apos;re free
</div>
)}

For search-ability, it's recommended you have files for localization/internationalization and call them into your app.

The above solutions work only in some cases. It wasn't working for me. In my case, I think it's because we're also using prettier in our project. To resolve the error, I wrapped the copy in backticks.

const func = () => {
return (
<div>
{`
You're free.
`}
</div>
)
}

This works for me with no eslint errors:

const func = () => {
return (
<div>
{"you're"} free
</div>
)
}

By the way, you can disable this kind of warnings by adding

"rules": { "react/no-unescaped-entities": 0 }

to your .eslintrc file.

I had the same issue with next.js what I did was to open the .eslintrc.json and add the following:

{
"rules": { "react/no-unescaped-entities": 0 }
}

Now my .eslintrc.json will look as follows:

{
"extends": "next/core-web-vitals",
"rules": { "react/no-unescaped-entities": 0 }
}

One way to fix the react/no-unescaped-entities error is by assigning the text with the escape character in it to a variable and then referencing the variable in the JXS.

Further reading:

const func = () => {
const text = `you're free`;
return (
<div>
{text}
</div>
)}

You can do 2 things,

  1. It can be escaped with &apos;

e.g.

const func = () => {
return (
<div >
you&apos;re free
</div>
)}
  1. Or you need to disable ESLint rules, for disable the ESLint rules, first find .eslintrc.json in project directory, then paste these lines there.

{
   "extends": "next/core-web-vitals",
   "rules": {
      "react/no-unescaped-entities": "off",
      "@next/next/no-page-custom-font": "off"
   }
}

Using backtick is more elegant to avoid this mistake :

const func = () => {
return (
<div >
{`you're free`}
</div>
)}