ST8*_*T80 3 javascript reactjs
是否可以根据 IF/OR 语句呈现元素?
我试过类似的东西:
{!this.props.this || this.props.that && <button>Some button</button>}
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
是的,这是可能的。使用三元运算符:
{
(!this.props.this || this.props.that) ? <button /> : null
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用React.Fragment来渲染更复杂的元素结构而无需容器,例如
{
this.props.test ? (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
) : null
}
Run Code Online (Sandbox Code Playgroud)
请注意,当您返回null 时, React 会将其视为无需渲染。