我可以使用箭头功能而不是React Hooks的普通功能吗?

问题描述 投票:2回答:3

是否可以将箭头函数与新的React Hook语法一起使用?会有什么不同和/或这会导致问题吗?

文档语法:

function Example() {

  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

箭头功能:

 const Example = () => {

  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
reactjs react-hooks
3个回答
5
投票

简短的回答是:是的,你可以。

箭头函数和函数声明/表达式不等效。但是,如果要替换的函数不使用thisarguments并且不使用new调用,那么您可以自由使用您喜欢的任何样式。


8
投票

使用functionconst声明功能组件之间的区别与functional expressionsfunctional declaration之间的区别相同

例如Function declarations在执行任何代码之前加载,而Function expressions仅在解释器到达该代码行时加载,即渲染使用function语法创建的功能组件可以在代码中定义之前完成,而如果使用expression定义它然后需要在使用前声明

因此,简而言之,function declarations被悬挂,而function expressions则没有

在使用上述两种语法创建组件方面,只要您使用卷入帐户,就可以使用它们


1
投票

一样的。每个函数与箭头函数的差异都是相同的(没有它自己的范围)但是对于反应钩子它是相同的

© www.soinside.com 2019 - 2024. All rights reserved.