所以现在我们不能使用钩子作为旧样式的事件函数旁边禁用警告什么是调用不违反规则的事件函数的最佳方法
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>
);
}
使用钩子,创建内联箭头函数的性能损失可以忽略它对类组件的好处,因此您不必担心渲染中的箭头函数。
您可以禁用此eslint规则。
但是你仍然通过编写increment
方法并使用useCallback
钩记忆它来改进你的代码
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(0);
const increment = React.useCallback(() => {
setCount(prev => prev+1);
}, [])
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>
Click me
</button>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>