我有一个函数,该函数需要几个布尔值,并且如果为true,则应该为每个布尔值呈现一个html元素。这就是我想做的:
>>> from math import isclose
>>> l = [0.85, 0.85, 0.15, 0.15]
>>> s = sum(l)
>>> isclose(s, round(s))
True
该片段现在不起作用。我可以有条件地渲染一个元素(例如,如果删除后续的function renderThis (first, second, third) {
if (!(first || second || third)) {
return <span>each input is false</span>
}
return (
//README: This part below doesn't work. How can I conditionally render these span tags below?
<React.Fragment>
{
first
? <span>First is true</span>
: null
second
? <span>Second is true</span>
: null
third
? <span>Third is true</span>
: null
credit
}
</React.Fragment>
)
}
和first
变量及其关联的代码,则可以渲染second
,但不能全部渲染三个元素。如何在此处有条件地呈现所有三个变量?
答案 0 :(得分:4)
将返回的元素转换为array
。您无法返回相邻的jsx
<React.Fragment>
{
[
true ? <span key='1'>First is true</span>: null,
true ? <span key='2'>Second is true</span>: null,
false ? <span key='3'>Third is true</span>: null
]
}
</React.Fragment>
如果仅返回数组,则不需要Fragment
return [
true ? <span>First is true</span>: null,
true ? <span>Second is true</span>: null,
false ? <span>Third is true</span>: null
]
此外,您不能从同一条语句返回相邻的jsx
,但是可以返回相邻的一元语句
return(
<>
{true ? <span /> : null}
{false ? <span /> : null}
</>
)
答案 1 :(得分:1)
如果要根据每个跨度的条件渲染所有三个跨度,则可以执行以下操作:
function renderThis(first, second, third) {
if (!(first || second || third)) {
return <span>each input is false</span>;
}
return (
//README: This part below doesn't work. How can I conditionally render these span tags below?
<React.Fragment>
{first && <span>First is true</span>}
{second && <span>Second is true</span>}
{third && <span>Third is true</span>}
</React.Fragment>
);
}
答案 2 :(得分:-1)
Array
方法对我来说似乎过于复杂。为什么不只是这个?
<React.Fragment>
{true && <span>First is true</span>}
{true && <span>Second is true</span>}
{false && <span>Third is true</span>}
</React.Fragment>