本文介绍了是否可以在 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... 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:19