是否可以在 React 渲染函数中使用 if...else... 语句?
<p>基本上,我有一个react组件,它的<code>render()</code>函数体如下:(这是我理想的一个,这意味着它目前不起作用)</p>
<pre class="brush:js;toolbar:false;">render(){
return (
<div>
<Element1/>
<Element2/>
// note: logic only, code does not work here
if (this.props.hasImage) <ElementWithImage/>
else <ElementWithoutImage/>
</div>
)
}
</pre>
<p><br /></p>
实际上有一种方法可以完全满足OP的要求。只需渲染并调用匿名函数,如下所示:
render () { return ( <div> {(() => { if (someCase) { return ( <div>someCase</div> ) } else if (otherCase) { return ( <div>otherCase</div> ) } else { return ( <div>catch all</div> ) } })()} </div> ) }不完全一样,但有解决方法。 React 文档中有一个关于条件渲染的部分,您应该看一下。以下是使用内联 if-else 可以执行的操作的示例。
render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> {isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> )} </div> ); }您还可以在渲染函数内处理它,但在返回 jsx 之前。
if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; } return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> );还值得一提的是 ZekeDroid 在评论中提出的内容。如果您只是检查条件并且不想呈现不符合条件的特定代码段,则可以使用
&& 运算符。return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> );