我在 React.js 中使用三元运算符时遇到问题

I have a problem using the Ternary Operator in React.js

我有一个页面应该自动生成部分。除三元运算符外,一切都可以正常传输。

我使用的数据:

carList = [
    {
        id: 0,
        brand: "Lorem",
        model: "Lorem",
        dealer: "Lorem",
        main_image: "Lorem",
        sections: [
            {
                id: 0,
                section_type: "",
                section_title: "Lorem",
                section_text: "Lorem Lorem Lorem Lorem Lorem",
                image_left: "Lorem1.png",
                image_center: null,
                image_right: null
            }
       ]
  }

重要提示:数据是手动输入的,不是从 JSON

导入的

如果“image_left”或“right”为空,当我想检查三元运算符时出现问题。

它们是这样发送的:

const { car_id } = this.state;

    const sections = this.carList[car_id].sections.map((section, index) => (
        <CarContent data={this.carList} car_id={this.state.car_id} section_id={this.carList[car_id].sections[index].id} />
    ))

这是他们收到的方式:

const CarContent = (props) => {
const { car_id, data, section_id } = props;
const section = data[car_id].sections[section_id];

return (
    <div className={section.section_type}>
        <div className="section_images">
            {section.image_left !== null ? <div className="image_left"> // Here < ------
                <img src={section.image_left} alt="" />
            </div> : ""}
            {(section.image_right !== null) ? <div className="image_right"> // And here < ------
                <img src={section.image_right} alt="" />
            </div> : ""}
        </div>
    </div>
  );
}

当我想检查例如“section_text”是否为空时,也会发生同样的情况。我只是希望给定的组件在它为空或 null

时不会出现

您获取 section 的方式不正确。此示例在这里有效,因为您的索引和部分恰好是 0 。但如果您的 sectionId10 并且它所在的索引是 5,这将是一个问题。使用您当前的代码,您将获取索引 10 中的部分。

const section = data[car_id].sections.find(section => section.id === section_id);

我想你要找的是条件渲染。

{
  section.image_left && (
    <div className="image_left">
      <img src={section.image_left} alt="" />
    </div>
  );
}

仅当 section.image_left 中有值时才呈现 div 。

注意这里的运算符&&。

{section.image_right && 
   (<div className="image_right">
     <img src={section.image_right} alt="Give a descriptive alt here"/>
   </div>)
}

这会检查 image_right 是否为空或 null。

  • 如果不是,那么它将使用里面的 img 呈现 div。
  • 如果为空或 null,则不会呈现 div 和 img.