[英]How to render jsx with conditions using react?
我想使用 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。
有人可以帮我解决这个问题。 谢谢。
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>
}
);
}
为了简化代码,您还可以将条件分配给 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>
}
);
}
您还可以在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.