是否可以在 React 渲染函数中使用 if...else... 语句?

编程入门 行业动态 更新时间:2024-10-26 13:26:12
本文介绍了是否可以在 React 渲染函数中使用 if...else... 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

基本上,我有一个 react 组件,它的 render() 函数体如下:(这是我理想的一个,这意味着它目前不起作用)

render(){返回 (<div><元素 1/><元素2/>//注意:代码在这里不起作用if (this.props.hasImage) else

)}

解决方案

不完全是这样,但有解决方法.React 的文档中有一节关于条件渲染,你应该看看.下面是使用内联 if-else 可以执行的操作的示例.

render() {const isLoggedIn = this.state.isLoggedIn;返回 (<div>{已登录?(<LogoutButton onClick={this.handleLogoutClick}/>) : (<LoginButton onClick={this.handleLoginClick}/>)}

);}

你也可以在render函数内部处理它,但是在返回jsx之前.

if (isLoggedIn) {button = <LogoutButton onClick={this.handleLogoutClick}/>;} 别的 {button = <LoginButton onClick={this.handleLoginClick}/>;}返回 (<div><问候 isLoggedIn={isLoggedIn}/>{按钮}

);

还值得一提的是 ZekeDroid 在评论中提出的内容.如果您只是检查条件并且不想呈现不符合要求的特定代码段,则可以使用 &&运算符.

返回 (<div><h1>你好!</h1>{unreadMessages.length >0 &&<h2>您有 {unreadMessages.length} 条未读消息.}

);

Basically, I have a react component, its render() function body is as below: (It is my ideal one, which means it currently does not work)

render(){ return ( <div> <Element1/> <Element2/> // note: code does not work here if (this.props.hasImage) <MyImage /> else <OtherElement/> </div> ) }

解决方案

Not exactly like that, but there are workarounds. There's a section in React's docs about conditional rendering that you should take a look. Here's an example of what you could do using inline if-else.

render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> {isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> )} </div> ); }

You can also deal with it inside the render function, but before returning the jsx.

if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; } return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> );

It's also worth mentioning what ZekeDroid brought up in the comments. If you're just checking for a condition and don't want to render a particular piece of code that doesn't comply, you can use the && operator.

return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> );

更多推荐

是否可以在 React 渲染函数中使用 if...else... 语句?

本文发布于:2023-08-02 18:01:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279941.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   函数   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!