无法找到如何在jsx表达式中正确编写三元运算符

问题描述 投票:-1回答:1

我有一个三元运算符,我想在jsx表达式中添加。每次尝试添加时,反应都会给我一个错误。该错误表明jsx表达式必​​须具有一个父元素。这是我的代码:

import React, { useState, useContext } from 'react'
import uuid from 'uuid/v1'
import { NavContext } from '../contexts/NavContext';
import { VegetarianContext } from '../contexts/VegetarianContext';

const BaseLayers = (props) => {
let tacos = props.tacos;
const [background, setBackground] = useState({ clickedItem: '' });
let { toggleNav } = useContext(NavContext);
**let { isVegetarian } = useContext(VegetarianContext);**
return (
    <div className='base-layers'>
    <img className="menu" src={require("../img/tacomenu.png")} onClick={toggleNav} />
    <div className="base-layers-info" >START BY CHOOSING A BASE LAYER</div>
      { Array.isArray(tacos.base_layers) && tacos.base_layers.map(item => {
         return <div className="base-layer" key={uuid()} id={item.title} style={{ backgroundColor: (background.clickedItem === item.title) ? '#0892d0' : 'red' }} >
                    **{ isVegetarian ? ( <div>The user is vegetarian</div> ) : (**
                    <h4 className="base-layer-title">{ item.title }</h4>
                    <img src={require('../img/taco-cards.jpg')} alt="tacomenu" />
                    <div className="base-layer-ingredients-container">
                    { item.ingredients.map(item => {
                        if(typeof item === 'string'){
                            return   <h6 className="base-layer-ingredients" key={uuid()}>{ item }</h6>
                        }
                        if(typeof item === 'object'){
                            return  <h6 className="base-layer-ingredients" key={uuid()}>{ item.title }</h6>
                            return  <h6 className="base-layer-ingredients" key={uuid()}>{ item.ingredients }</h6>
                        }
                    }) }
                    </div>
                    <button className="base-layer-button" onClick={(e) => {
                        props.setBaseLayer(e.target.parentElement.id);
                        setBackground({ clickedItem: e.target.parentElement.id });
                    }} >
                        Choose this base layer
                    </button>
                    <div className="base-layer-tags-container">
                    { item.tags.map(item => {
                        return   <h6 className="base-layer-tags" key={uuid()}>{ item }</h6>
                    }) }
                    </div>
                    ) }

                </div>
        })}

    </div>
);
}

 export default BaseLayers;
reactjs jsx ternary-operator
1个回答
0
投票

三元表达式的每一段都应包装为一个元素。如果要返回多个,我建议将它们包装在a中,以免在DOM中引入另一层。

{ isVegetarian ? 
  <div>
    The user is vegetarian
  </div>
  :
  <React.Fragment>
    <h4 className="base-layer-title">{ item.title }</h4>
    <img src={require('../img/taco-cards.jpg')} alt="tacomenu" />
  </React.Fragment>
}
© www.soinside.com 2019 - 2024. All rights reserved.