如何使用 ESlint 解决警告:Disallow Assignment in return Statement (no-return-assign)?

How to resolve warning with ESlint: Disallow Assignment in return Statement (no-return-assign)?

我在我的 React 应用程序中使用以下包来生成 Recaptcha 组件:https://github.com/appleboy/react-recaptcha

组件如下所示,带有 eslint 警告:

this.recaptchaRef 定义如下:this.recaptchaRef = React.createRef();

这个 ref 允许我在我的表单出现错误时重置 Recaptcha,如下所示:this.recaptchaRef.reset();

如何在不编写 ESlint 注释的情况下解决此错误?

箭头函数,如果 => 后面没有 {,则 return 将跟随任何表达式。目前,您的箭头函数正在将 event 分配给 this.recaptchaRef returning event。 (即使消费者完全忽略了 return 值,它仍然会产生 linting 错误。)因此,只需使用大括号来确保没有任何内容被 returned:

ref={(event) => {
  this.recaptchaRef = event;
}}

根据 Arrow functions 的文档,他们可以有 "concise body" 或通常的 "block body"。

In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.

所以在您使用的示例中,指定了 "concise body"。简洁 body 表示周围没有花括号。因此,即使没有 return 关键字,表达式也会被 returned。由于您想避免 returning 表达式,因此您需要将 body 更改为 "block body" 即在 => 运算符之后指定大括号,即

ref = {event => {
    this.recaptchaRef = event;
}};