如何在呈现React组件时添加逻辑if语句?

Chr*_*kes 21 reactjs

如果我的代码看起来像这样......

var Lounge = React.createClass({displayName: "Lounge",
  render: function() {
    return (
            React.createElement("a", {href:"/lounge/detail/" + this.props.id +  "/"},
            React.createElement("div", {className: "lounge"},
            React.createElement("h2", {className: "loungeAuthor"},
              this.props.author.name
            ),
            React.createElement("p", {className: "loungeArticle"},
              this.props.article
            ),
            React.createElement("img", {className: "loungeImage", src: this.props.image})
          )
        )
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

如果图像数据存在,我需要检查以仅渲染"img"组件.有人知道使用React解决这个问题的最佳方法吗?

Jon*_*nan 37

如果你想内联,你可以这样做:

{this.props.image && <img className="loungeImage" src={this.props.image}/>}

this.props.image && React.createElement("img", {className: "loungeImage", src: this.props.image})
Run Code Online (Sandbox Code Playgroud)

如果要检查的值是假的,但是会导致React呈现某些内容,就像空字符串一样,您可能希望通过使用!!以下内容将其转换为检查中的布尔等效值:

{!!this.props.image && <img className="loungeImage" src={this.props.image}/>}

!!this.props.image && React.createElement("img", {className: "loungeImage", src: this.props.image})
Run Code Online (Sandbox Code Playgroud)

  • 也许[关于整个条件渲染主题的一个很好的解读](https://www.robinwieruch.de/conditional-rendering-react/). (2认同)

Kon*_*kus 10

保持此逻辑内联以及使用JSX可能有助于提高可读性

import React from 'react';
import PropTypes from 'prop-types';
import s from './Lounge.css'; // See CSS Modules

// Stateless functional component (since there is no state)
function Lounge({ id, article, author, imageUrl }) {
  return (
    <a href={`/lounge/detail/${id}/`}>
      <span className={s.lounge}>
        <span className={s.author}>{author.name}</span>
        <span className={s.article}>{article}</span>
        {imageUrl && <img className={s.image} src={imageUrl} />} // <==
      </span>
    </a>
  );
}

// Props validation
Lounge.propTypes = {
  id: PropTypes.number.isRequired,
  article: PropTypes.string.isRequired,
  imageUrl: PropTypes.string,
  author: PropTypes.shape({
    name: PropTypes.string.isRequired
  }).isRequired
};

export default Lounge;
Run Code Online (Sandbox Code Playgroud)