React中能否在函数内调用import?如何基于props动态导入资源文件?
你现在的写法不生效的核心原因是:ES6的静态import语句是在编译阶段执行的,只能使用静态字符串作为路径,不支持运行时才确定的变量(比如组件接收的props),也不能写在函数/组件内部作用域。
下面是两种可行的解决方案:
方案1:将资源放在public目录直接拼接路径(最适配你的场景)
这个方案不需要导入操作,逻辑最简单,适合大体积的基因组数据文件,操作步骤:
- 把整个
genome_data文件夹移动到项目的public根目录下 - 组件内直接用props.id拼接资源路径即可
代码示例:
function View(props) { // 路径拼接,若项目部署不在域名根目录,可拼接环境变量的基础路径,例如Vite下使用`${import.meta.env.BASE_URL}genome_data/...` const basePath = `/genome_data/${props.id}` const assembly ={ name: props.id, sequence: { type: 'ReferenceSequenceTrack', trackId: 'GRCh38-ReferenceSequenceTrack', adapter: { type: 'IndexedFastaAdapter', fastaLocation: { uri: `${basePath}.fna`, faiLocation: `${basePath}.fna.fai`, gffLocation: `${basePath}.sorted.gff.gz`, gffTbiLocation: `${basePath}.sorted.gff.gz.tbi`, bwLocation: `${basePath}.bw` } // 其余逻辑保持不变 } } } // 组件其余原有逻辑 }
方案2:使用动态import()(仅当资源必须放在src目录时使用)
动态import是运行时执行的异步方法,支持传入变量路径,需要配合状态管理处理异步加载状态:
import { useEffect, useState } from 'react' function View(props) { const [resourceUrls, setResourceUrls] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { const loadResources = async () => { setLoading(true) // 动态导入对应id的资源,Vite环境下需要加/* @vite-ignore */注释避免编译报错 const [fasta, fai, gff, gfftbi, ssrbw] = await Promise.all([ import(`../genome_data/${props.id}.fna`), import(`../genome_data/${props.id}.fna.fai`), import(`../genome_data/${props.id}.sorted.gff.gz`), import(`../genome_data/${props.id}.sorted.gff.gz.tbi`), import(`../genome_data/${props.id}.bw`) ]) setResourceUrls({ fasta: fasta.default, fai: fai.default, gff: gff.default, gfftbi: gfftbi.default, ssrbw: ssrbw.default }) setLoading(false) } loadResources() }, [props.id]) // id变化时自动重新加载对应资源 if (loading) return <div>资源加载中...</div> const assembly ={ name: props.id, sequence: { type: 'ReferenceSequenceTrack', trackId: 'GRCh38-ReferenceSequenceTrack', adapter: { type: 'IndexedFastaAdapter', fastaLocation: { uri: resourceUrls.fasta, // 其余字段对应取resourceUrls内的属性即可 } } } } // 组件其余原有逻辑 }
内容的提问来源于stack exchange,提问作者AU_97_CB
相关产品推荐
相关产品推荐

