何时使用花括号以及何时在 React 中使用角度

问题描述

例如:

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}}?我知道我可以在大括号内使用函数,它是如何工作的?

解决方法

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

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

function renderAvatar(author) {
     return ...
}

Comment 组件

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

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

感谢大家的帮助!