jsx if else shorthand 隐藏元素
jsx if else shorthand to hide element
我能做到
<p>Company: {{this.state.user.company}}</p>
但有时公司没有价值。那么,如果公司的 属性 为空,我应该如何隐藏整个
?
我试过了
<p>({this.state.user.company} ? 'Company: ' + {this.state.user.company} : '')</p>
但是不行。
React 不会渲染虚假值,因此您可以使用 short-circuit evaluation。如果 this.state.user.company
是 null
,它将被 react 忽略。如果它是真实的,反应将在 &&
.
之后呈现元素
render() {
return (
<div>
{this.state.user.company &&
<p>Company: {this.state.user.company}</p>
}
</div>
);
}
Ori Drori 回答的替代语法(我觉得这更容易阅读):
render() {
return (
{this.state.user.company ? <p>Company: {this.state.user.company}</p> : null}
)
}
另一种选择:
render() {
if (!this.state.user.company) return (<p>Loading...</p>)
return (
<div>
<p>Name: {this.state.user.company.name}</p>
<p>Address: {this.state.user.company.address}</p>
<p>Creation date: {this.state.user.company.creation}</p>
</div>
)
}
您还可以将以下内容用于简写格式:
render() {
return (
{this.state.user.company ?? <p>Company: {this.state.user.company}</p>}
)
}
我能做到
<p>Company: {{this.state.user.company}}</p>
但有时公司没有价值。那么,如果公司的 属性 为空,我应该如何隐藏整个
?
我试过了
<p>({this.state.user.company} ? 'Company: ' + {this.state.user.company} : '')</p>
但是不行。
React 不会渲染虚假值,因此您可以使用 short-circuit evaluation。如果 this.state.user.company
是 null
,它将被 react 忽略。如果它是真实的,反应将在 &&
.
render() {
return (
<div>
{this.state.user.company &&
<p>Company: {this.state.user.company}</p>
}
</div>
);
}
Ori Drori 回答的替代语法(我觉得这更容易阅读):
render() {
return (
{this.state.user.company ? <p>Company: {this.state.user.company}</p> : null}
)
}
另一种选择:
render() {
if (!this.state.user.company) return (<p>Loading...</p>)
return (
<div>
<p>Name: {this.state.user.company.name}</p>
<p>Address: {this.state.user.company.address}</p>
<p>Creation date: {this.state.user.company.creation}</p>
</div>
)
}
您还可以将以下内容用于简写格式:
render() {
return (
{this.state.user.company ?? <p>Company: {this.state.user.company}</p>}
)
}