简体   繁体   English

可以在 React 无状态组件中定义 function 吗?

[英]is it ok to define a function inside a React stateless component?

Is it bad practice to define a function (like handleClick in the example below) inside a stateless component?在无状态组件中定义 function(如下例中的handleClick )是不好的做法吗? I was told that you should avoid doing so, but I can't find anything in the documentation to confirm it.有人告诉我你应该避免这样做,但我在文档中找不到任何东西来确认它。 If the answer is "yes" then why is defining a function into a class instead any better?如果答案是“是”,那么为什么将 function 定义为 class 会更好?

function MiniPalette(props) {
  const {classes } = props;
  

  function handleClick() {
    history.push(`palette/${id}`);
  }

  return (
    <div className={classes.root} onClick={handleClick}>
      <div className={classes.colors}>{miniColorBoxes}</div>
      <h5 className={classes.title}>
        {paletteName}
        <span className={classes.emoji}>{emoji}</span>
      </h5>
    </div>
  );
}

It is generally a bad practice in javascript, not in React in particular.这在 javascript 中通常是一种不好的做法,尤其是在 React 中。 Basically if you declare a function inside a function, every time you call the parent function it will initialize the child function as well and it is a waste of resource. Basically if you declare a function inside a function, every time you call the parent function it will initialize the child function as well and it is a waste of resource. For details you can also check out this: https://code.tutsplus.com/tutorials/stop-nesting-functions-but-not-all-of-them--net-22315有关详细信息,您还可以查看: https://code.tutsplus.com/tutorials/stop-nesting-functions-but-not-all-of-them--net-22315

Viet is correct in that it's a waste of resources. Viet 是正确的,因为这是对资源的浪费。 A good way to look at the component tree is that you want to process data at the top and near the bottom your focus is only in rendering the data.查看组件树的一个好方法是,您希望在顶部和底部附近处理数据,您的重点仅在于呈现数据。 If for example you need a way to manipulate the data and update state, I would suggest passing hooks down or diverting to useContext().例如,如果您需要一种操作数据和更新 state 的方法,我建议将挂钩向下传递或转移到 useContext()。 This will also keep your code cleaner and you can eventually make use higher order components for like-functions.这也将使您的代码更干净,您最终可以使用更高阶的组件来实现类似的功能。

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

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