【问题标题】:When to use curly braces and when angle in React在 React 中何时使用花括号以及何时使用角度
【发布时间】:2021-05-04 17:38:43
【问题描述】:

例如:

function Avatar(props) {
  return (
    <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
  );
}

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />
        <div className="UserInfo-name">
          {props.author.name}

为什么我不能使用 {Avatar(props.author)} 或 {Avatar() user={props.author}}?我知道我可以在花括号内使用函数,它是如何工作的?

【问题讨论】:

  • 因为你不想只调用Avatar作为一个函数,你想创建一个React组件,如果你只是调用一个随机函数,React不会将它注册为组件。如果你真的决定调用某个东西,你可以使用React.createElement方法(更多细节见reactjs.org/docs/jsx-in-depth.html
  • 我已将我的函数转换为箭头函数,现在它可以完美运行了。此外,我找到了一篇文章,它说:直接将功能组件调用为函数而不是使用 React.createElement 挂载它们要快得多。我更加困惑了。
  • 这就是 JSX 的意义所在,它为您提供类似 HTML 的语法,以便您的代码更易于阅读。不过,你是 by no means forced 来使用 JSX。
  • @AndrewKruglik 如果您将Avatar 作为函数调用,它只会将一些元素注入到父组件中,但它本身不会被注册为组件,因此它无法拥有声明或使用钩子。是的,它比 React.createElement 更快,因为你跳过了创建 React 组件。

标签: reactjs react-props high-order-component


【解决方案1】:

我找到了答案:将函数声明为&lt;Component/&gt;,使其对 React 可见,并允许您使用生命周期方法和钩子。如果你将它用作函数:React 只看到从它返回的结果,但它的运行速度要快约 45 倍。

感谢大家的帮助!

【讨论】:

    【解决方案2】:

    好吧,如果孩子收到道具并返回jsx,它将被视为React Element或React Node,在这种情况下您可以像&lt;Avatar user={props.author} /&gt;一样使用它。

    如果你想在Comment 中使用函数,就像这样:

    function renderAvatar(author) {
         return ...
    }
    

    Comment 组件

       <div>
          {renderAvatar(props.author)}
       </div>
    

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 2021-02-09
      • 1970-01-01
      • 2014-04-23
      • 2015-02-24
      • 2013-10-01
      • 1970-01-01
      • 2010-10-24
      • 2013-07-26
      相关资源
      最近更新 更多