reactjs 当Map到数组时,是否有方法检查文件是图像还是视频?

u7up0aaq  于 2023-03-08  发布在  React
关注(0)|答案(2)|浏览(131)

我正在处理我的Portfolio,目前我正在Map一个数组,以创建一个包含多个图像的项目列表作为Slider(Swiper)组件。
现在我需要的可能性,也包括视频,而不是一个图像。所以我想我可能需要的东西,检查如果传递的文件是一个图像或视频,然后选择合适的html标签(/)有一个简单的方法来实现这一点吗?
My Code示例(缩减为相关部分):
Map项目组件以生成项目:

{allData.map((project) => (
  <Project id={project.id} text={project.title} vids={project.videos} imgs={project.images} description={project.info} />
))}

将数据传递到项目组件:

const Project = ({ text, vids, imgs, description }) => {
                        {imgs.map(e => (
                            <SwiperSlide>
                                <div className="image-container">
                                    <img className="image-center" src={e} />
                                    
                                </div>
                            </SwiperSlide>
                        ))}
                        
                        {vids.map(video => (
                            <SwiperSlide>
                                <video src={video} />
                            </SwiperSlide>
                        ))}

阵列的外观:

import img1 from './img/1.jpg';
import img2 from './img/2.jpg';
import img3 from './img/3.jpg';
import video1 from './video/1.mp4';

const allData = [
    {
        id:1,
        images: [img1, img2, img3]
        title: 'Example-title',
    },
    {
        id:2,
        images: [img3]
        videos: [video1]
        title: 'Example-title',
    }
export default allData

有人能帮我一下吗?

mwg9r5ms

mwg9r5ms1#

试试这个:

const isImage = ['.gif','.jpg','.jpeg','.png']; //you can add more
 const   isVideo =['.mpg', '.mp2', '.mpeg', '.mpe', '.mpv', '.mp4'] // you can add more extention
    
//merge image and video in single array

const Project = ({ text, files, description }) => {
                        {files.map(e => (
                            <SwiperSlide>
                                <div className="image-container">
                                   { isImage?.includes(e) && <img className="image-center" src={e} />  }
                                      {isVideo?.includes(e) && <video src={e} />  }
                                </div>
                            </SwiperSlide>
                        ))}
}

谢谢。

e37o9pze

e37o9pze2#

const videoExtensions = ['.mpg', '.mp2', '.mpeg', '.mpe', '.mpv', '.mp4'] //you can add more extensions
const imageExtensions = ['.gif', '.jpg', '.jpeg', '.png'] // you can add more extensions

let status

const isImage = (v) => {
  imageExtensions.map((e) => {
    status = v.includes(e);
  })
  return status
};
const isVideo = (v) => {
  videoExtensions.map((e) => {
    status = v.includes(e);
  })

  return status
};

// To use
console.log(isImage("https://gist-cdn.azureedge.net/videos/20233/94044102-46bf-4a15-a674-48e63fdac6bf.mp4"))

console.log(isVideo("https://gist-cdn.azureedge.net/videos/20233/94044102-46bf-4a15-a674-48e63fdac6bf.mp4"))

相关问题