[英]ReactJS conditional rendering IF/OR
Is it possible to render an element based on a IF/OR statement? 是否可以基于IF / OR语句渲染元素?
I tried something like: 我尝试了类似的东西:
{!this.props.this || this.props.that && <button>Some button</button>}
but that doesn't work. 但这不起作用。
Yes, it's possible. 是的,有可能。 Use ternary operator : 使用三元运算符 :
{
(!this.props.this || this.props.that) ? <button /> : null
}
You can also use React.Fragment to render more complex elements structure without container, for example 您还可以使用React.Fragment在没有容器的情况下渲染更复杂的元素结构
{
this.props.test ? (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
) : null
}
Note, that when you return null React treats it as nothing to render. 注意,当您返回null时, React会将其视为没有任何可呈现的内容。
I assume you want to know the equivalent of 我想你想知道相当于
if (!this.props.this || this.props.that) {
// Render the button
}
The reason your code doesn't work that way is because of the precedence of &&
and ||
您的代码无法以这种方式工作的原因是因为&&
和||
的优先级 . 。 The &&
is evaluated first, but you really want the combined condition to evaluate first. 首先对&&
进行评估,但您确实希望首先对组合条件进行评估。
You could use a ternary as others have suggested, but all you technically need is parentheses 您可以像其他人建议的那样使用三元数,但是技术上您需要的只是括号
{(!this.props.this || this.props.that) && <button>Some button</button>}
That way, you don't need a redundant null
这样,您就不需要多余的null
The official documentation on this is pretty good. 官方文档是相当不错的。 I find it cleanest to use ternary operators, which work as follows: 我发现使用三元运算符最干净,其工作方式如下:
{(!this.props.this || this.props.that) ? <button>Some button</button> : null }
You can of course have a different component render if false instead of just null
. 当然,如果为false而不是null
则可以具有不同的组件呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.