简体   繁体   English

在变量中使用 JSX VS 使用函数在 React 中返回 JSX

[英]Using JSX in a variable VS using a function to return the JSX in React

I'd like to create a functional React component that will not require the usage of any hooks/props.我想创建一个不需要使用任何钩子/道具的功能性 React 组件。 In this scenario is there a benefit of doing the following:在这种情况下,执行以下操作是否有好处:

const Test = (
  <p>
    Hello World
  </p>
);

const MainComponent = () => {
  return (
    <div>
      {Test}
    </div>
  );
};

Instead of doing the following:而不是执行以下操作:

const Test = () => {
  return (
    <p>
      Hello World
    </p>
  );
};

const MainComponent = () => {
  return (
    <div>
      <Test />
    </div>
  );
};

The first example is not really a component.第一个示例并不是真正的组件。 It's more of a shortcut for a static html structure you want to reuse.它更像是要重用的静态 html 结构的快捷方式。 Therefore, it has no state or props any react component has.因此,它没有任何反应组件具有的状态或道具。 If the Component you want to use does not have any state or props, It won't change anything considering the sole view, but if ever you want to add props or state to that component, having it as a variable will require you to fully turn the variable into a real component.如果您要使用的组件没有任何状态或道具,考虑到单一视图,它不会改变任何东西,但是如果您想向该组件添加道具或状态,将其作为变量将需要您完全将变量转换为实际组件。 Considering the small amount of time you win by using a variable and the potentially huge amount of time you might loose someday, I'd recommend not to use Variables like above.考虑到您通过使用变量赢得的时间很少,而有一天您可能会失去大量时间,我建议不要使用上述变量。 (And to answer your question about benefits, there are no benefits to doing that) (为了回答您关于福利的问题,这样做没有任何好处)

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

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