渲染 React 子组件,具有条件渲染和一个通用包装 html 元素

问题描述 投票:0回答:1

我有一个 React 组件:

const Options = () => {

  // Option logic
  
  if (isOptionOne) {
    return <OptionOne />;
  }

  if (isOptionTwo) {
    return <OptionTwo />;
  }

  if (isOptionThree) {
    return <OptionThree />;
  }

  return null;
};

我在父组件中渲染此组件:

const ParentComponent = () => {

    <ComponentA />
    <span css={styles.container}
      <Options />
    </span>

  };

<span>
标签移动到子组件(
<Options />
)的干净方法是什么,因为我只想在
<Options />
组件不返回 null 时渲染此 html 标签。

reactjs if-statement conditional-rendering
1个回答
0
投票

您应该检查选项组件是否返回 null 或组件 如果返回组件则渲染,否则不渲染。

您可以使用 Boolean() 来检查它是否返回 null 或组件。

如果返回 false 则不渲染 html 标签,如果返回则渲染。

代码如下所示:

const ParentComponent = () => {
  const shouldRenderOptions = Boolean(<Options />);

  return (
    <ComponentA />
    {shouldRenderOptions && (
      <span css={styles.container}>
        <Options />
      </span>
    )}
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.