繁体   English   中英

React Hooks 和 jsx-no-lambda 警告

[英]React Hooks and jsx-no-lambda warning

所以现在除了禁用警告之外,我们不能将钩子用作旧样式的事件函数,调用不违反规则的事件函数的最佳方法是什么

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钩子useCallback它来改进您的代码。 这在您尝试将处理程序传递给嵌套组件时特别有用,然后您可以使用React.memo优化重新渲染

 const Button = React.memo(function Btn({increment}) { return ( <button onClick={increment}> Click me </button> ) }) 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 increment={increment}/> </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"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM