解决方法:
<div ref={(el) => { this.myCustomEl = el }} />
解释:
您当前的代码相当于:
<div ref={(el) => { return this.myCustomEl = el }} />
您正在返回 this.myCustomEl = el 的结果。在您的代码中,这并不是一个真正的问题——但是,当您不小心使用赋值 (=) 而不是比较器(== 或 ===)时,会发生编程中最令人沮丧的错误之一,例如:
// This function will always return **true**, surprisingly
function isEqual(a, b) {
// The warning would be thrown here, because you probably meant to type "a===b". The below function will always return true;
return a=b;
}
let k=false;
let j=true;
if(isEqual(k,j)){
// You'll be very, very, very confused as to why this code is reached because you literally just set k to be false and j to be true, so they should be different, right? Right?
thisWillExecuteUnexpectedly();
}
在上述情况下,编译器警告是有意义的,因为 k=true 的计算结果为 true(与 k===true 不同,这可能是您要键入的内容)并导致意外行为。因此,当您返回一个赋值时,eshint 会发出通知,假定您打算返回一个比较结果,并让您知道您应该小心。
在你的情况下,你可以通过简单地不返回结果来解决这个问题,这是通过添加括号 {} 并且没有返回语句来完成的:
<div ref={(el) => { this.myCustomEl = el }} />
您还可以像这样调整 eshint 警告:
https://eslint.org/docs/rules/no-return-assign