简体   繁体   English

如何使用反应渲染带有条件的jsx?

[英]How to render jsx with conditions using react?

i want to render jsx based on condition using react.我想使用 react 根据条件渲染 jsx。

what i am trying to do?我想做什么?

if items.length <= 0 and shared_items.length <= 0 i want to display some content.如果 items.length <= 0 和 shared_items.length <= 0 我想显示一些内容。

if items.length > 0 or shared_items.length > 0 i want to display other content.如果 items.length > 0 或 shared_items.length > 0 我想显示其他内容。

below is my code,下面是我的代码,

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>
        }
    );
}

the second condition code is unreachable.第二个条件码不可达。 not sure how to render jsx based on condition.不知道如何根据条件渲染 jsx。

could someone help me fix this.有人可以帮我解决这个问题。 thanks.谢谢。

The or operator is wrong. or 运算符是错误的。

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

In order to simplify your code, you can also assign your condition to a boolean variable为了简化代码,您还可以将条件分配给 boolean 变量

function Parent() {
    const conditionA = items.length <= 0 && shared_items.length <= 0  ? true : false;
    const conditionB = items.length > 0 || shared_items.length > 0 ? true: false;
    return(
        {conditionA && 
            <div>
                <span> first</span>
            </div>
        }
        {conditionB && //unreachable code here
            <div>
                <Button> click</Button>
                <span> second </span>
            </div>
        }
    );
}

You can also create this component for conditional render in react .您还可以在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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM