繁体   English   中英

Map 和 React JSX 中的 Switch

[英]Map and Switch in React JSX

我有一点麻烦,我有一个 React Function 组件,我需要map然后在我的 JSX 中switch

我知道我应该尝试在 return 语句之外/之前执行此操作,但我似乎无法弄清楚,因为呈现的组件依赖于通过组件道具传递的数组。

以下是我在退货声明中试图实现的目标

{(() => {
  files.map((file, index) =>
    let type = getFileType(file)
    switch(type){
      case 'image':
        return (
          <div className="item">
            <img src={file}/>
          </div>
        )
      default:
       return;
    }
  })()
}

我显然忽略了一些重要的事情,我已经做了一段时间但似乎无法理解。 任何帮助将不胜感激。

您需要从 Immediate-Invoked Function return 。尝试如下所示。

{(() => {
  return files.map((file, index) => {
    let type = getFileType(file);
    switch (type) {
      case "image":
        return (
          <div className="item">
            <img src={file} />
          </div>
        );
      default:
        return null;
    }
  });
})()}

这样的事情应该有效:

import React from "react";



const files = ["file01.img", "file02.other", "file03.img"];


const getFileType = (file) => {
    if (file.endsWith(".img")) return "image";
    return "other";
};



export default function YourComponent() {

    return (

        <div>

            { files.map( (file, index) => {
                
                let type = getFileType(file)
                
                switch (type) {
                    case 'image':
                        return (
                            <div className="item">
                                <p>image</p>
                            </div>
                        )
                    default:
                        return <p>other</p>
                }
                
            } )}

        </div>

    );

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM