我有麻烦导入img使用本地数据.json文件,它有一个路径对象(REACT)



我无法在我的react应用程序中导入照片,错误提示为" error: Cannot find module " ./…/assets/planet-mercury.svg "

我使用json文件来获取img的路径

我的应用程序认为我的路径看起来像这样'./../assets/planet-mercury.svg',但当我试图记录它时,我看到这个路径'./assets/planet-mercury.svg'(这是我的json文件中的路径)。这意味着我的完整路径应该是这样的'./../assets/planet-mercury.svg'

代码:

const [currentPlanet,setCurrentPlanet]=useState(data[0])
const {name} = useParams();
useEffect(() => {
const planet = data.find((item)=>item.name===name)
setCurrentPlanet(planet);
}, [name])
const photo = require('../.'+currentPlanet.images.planet).default
return (
<section id={planetStyle.planet}>
<div className="container">
<div>
<img alt={currentPlanet.name} src={photo} />
</div>
</div>
</section>
)

您正在使用"为了导入图像文件。

这不会在React应用程序中工作,至少不是开箱即用的。

我明白你想做什么,我认为一个更好的解决方案是使用一个自定义的react钩子来导入你的图像。这样的:

function useDynamicSVGImport(name, options = {}) {
const ImportedIconRef = useRef();
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
const { onCompleted, onError } = options;
useEffect(() => {
setLoading(true);
const importIcon = async () => {
try {
ImportedIconRef.current = (
await import(`./${name}.svg`)
).ReactComponent;
if (onCompleted) {
onCompleted(name, ImportedIconRef.current);
}
} catch (err) {
if (onError) {
onError(err);
}
setError(err);
} finally {
setLoading(false);
}
};
importIcon();
}, [name, onCompleted, onError]);
return { error, loading, SvgIcon: ImportedIconRef.current };
}

相关内容

最新更新