React,如何在 div 中使用 if 条件来更改其类名?

React, how to use if condition inside a div to change its className?

我正在尝试使用 API 获取数据并将其循环用于横幅图像。
我得到了数据。它工作正常。这是获取数据的代码。

///Retrieving data using API
const [post, setPost] = useState(null);    
  useEffect(() => {
    axios.get(global.url+'api/welcome').then(response => {
      setPost(response.data);
    });
  }, []);

现在,我想在横幅中显示图片。如图所示,在第一个循环中 div class 需要 <div className="carousel-item active">。从第二个循环中需要删除活动,如下所示:<div className="carousel-item">.

////Looping for banner images
    post[1].data.map((banner_image) => (
     <div>    
       <div className="carousel-item active">
        <img src="image source here" className="d-block w-100" alt="" />
       </div>
     </div> ))

这种情况下如何使用if条件?我对 React Js 很陌生。
提前谢谢你。

你可以这样在你的 JSX 中做条件:

Notice the {} for className.

 post[1].data.map((banner_image, index) => (
     <div>    
       <div className={"carousel-item " + index === 0 ? "active" : ""}>
        <img src="image source here" className="d-block w-100" alt="" />
       </div>
     </div> ))

试试这个

////Looping for banner images
    post[1].data.map((banner_image, idx) => (
     <div key={idx}>    
       <div className={`carousel-item ${idx === 0 ? "active" : ""}`}>
        <img src="image source here" className="d-block w-100" alt="" />
       </div>
     </div> ))

您可以在 JSX 中使用模板文字。

post[1].data.map((banner_image, index) => (
     <div key={`uui-${index}`}>    
       <div className={`carousel-item ${index === 0 ? 'active' : ''}`}>
        <img src="image source here" className="d-block w-100" alt="" />
       </div>
     </div> ))