个人技术分享

您的组件通常需要根据不同的条件显示不同的内容。在 React 中,你可以使用 JavaScript 语法(如语句、 和运算符)有条件地呈现 JSX。if&&? :

有条件地返回 JSX

假设您有一个渲染多个 s 的组件,可以将其标记为打包或未打包:PackingListItem

function Item({ name, isPacked }) {
  return <li className="item">{name}</li>;
}

export default function PackingList() {
  return (
    <section>
      <h1>Sally Ride's Packing List</h1>
      <ul>
        <Item 
          isPacked={true} 
          name="Space suit" 
        />
        <Item 
          isPacked={true} 
          name="Helmet with a golden leaf" 
        />
        <Item 
          isPacked={false} 
          name="Photo of Tam" 
        />
      </ul>
    </section>
  );
}

如果 prop 是 ,则此代码返回不同的 JSX 树。通过此更改,某些项目在末尾会打勾:isPackedtrue

function Item({ name, isPacked }) {
  if (isPacked) {
    return <li className="item">{name} ✔</li>;
  }
  return <li className="item">{name}</li>;
}

export default function PackingList() {
  return (
    <section>
      <h1>Sally Ride's Packing List</h1>
      <ul>
        <Item 
          isPacked={true} 
          name="Space suit" 
        />
        <Item 
          isPacked={true} 
          name="Helmet with a golden leaf" 
        />
        <Item 
          isPacked={false} 
          name="Photo of Tam" 
        />
      </ul>
    </section>
  );
}

有条件地不返回任何内容null 

在某些情况下,您根本不想渲染任何内容。例如,假设您根本不想显示包装好的商品。组件必须返回某些内容。在这种情况下,您可以返回:null

if (isPacked) {
  return null;
}
return <li className="item">{name}</li>;

如果为 true,则组件将不返回任何内容。否则,它将返回 JSX 进行渲染。isPackednull

function Item({ name, isPacked }) {
  if (isPacked) {
    return null;
  }
  return <li className="item">{name}</li>;
}

export default function PackingList() {
  return (
    <section>
      <h1>Sally Ride's Packing List</h1>
      <ul>
        <Item 
          isPacked={true} 
          name="Space suit" 
        />
        <Item 
          isPacked={true} 
          name="Helmet with a golden leaf" 
        />
        <Item 
          isPacked={false} 
          name="Photo of Tam" 
        />
      </ul>
    </section>
  );
}