如何使用react使用条件渲染jsx?

莎丽莎

我想根据条件使用React渲染jsx。

我想做什么?

如果items.length <= 0和shared_items.length <= 0我想显示一些内容。

如果items.length> 0或shared_items.length> 0,我想显示其他内容。

下面是我的代码,

function Parent() {
    return(
        {items.length <= 0 && shared_items.length <= 0 && 
            <div>
                <span> first</span>
            </div>
        }
        {items.length > 0 or shared_items.length > 0 && //unreachable code here
            <div>
                <Button> click</Button>
                <span> second </span>
            </div>
        }
    );
}

第二个条件代码不可访问。不知道如何根据条件呈现jsx。

有人可以帮我解决这个问题。谢谢。

弗林·帕特尔

您也可以在中创建该组件以进行条件渲染react

export default function App() {
  const items = [1, 2, 3, 4, 5];
  const shared_items = [3, 4, 5];

  const RenderFunc = () => {
    if (items.length <= 0 && shared_items.length <= 0) {
      return (
        <div>
          <span> first</span>
        </div>
      );
    }
    if (items.length > 0 || shared_items.length > 0) {
      return (
        <div>
          <button> click</button>
          <span> second </span>
        </div>
      );
    }
  };

  return (
    <div>
      <RenderFunc />
    </div>
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章