【发布时间】:2019-07-25 18:51:16
【问题描述】:
所以现在我们不能将钩子用作旧样式的事件函数,除了禁用警告之外,调用不违反规则的事件函数的最佳方法是什么
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> // Lambdas are forbidden in JSX attributes due to their rendering performance impact (jsx-no-lambda)
Click me
</button>
</div>
);
}
【问题讨论】:
-
const inc = () => setCount(prevCount => prevCount + 1);然后<Button onClick={inc}> -
这只是抑制警告但没有改善。
-
@Monsignor 实际上这个问题不再有用了,因为 tslint 已被弃用,并且带有 typescript 插件的官方 CRA eslint 默认没有此规则。而且是的,只是禁用这个警告是最好的解决方案,除非 lambdas 真的影响你的应用程序或组件的性能