我正在尝试在我的React组件之一中动态导入一些图像。图像的名称存储在JSON文件中,然后作为道具传递给组件。
这是传递数据的父组件:
const GridBlocks = gridItems.map(({ imageSrc, alt, ...textProps }, index) => (
<div key={`grid-section-${index}`} styleName="grid-section">
<ImageBlock imageSrc={imageSrc} alt={alt} />
<TextBlock {...textProps} />
</div>
));
现在我面临的问题是我显然不能
import prop from 'bar'
与往常一样,因为子组件不会知道“ prop”是什么。
我环顾四周,我认为解决方案应该看起来像这样? (除了您知道...运作中)。尤其是在“ require.context”周围,但我只是搞不清楚实现。
import React from 'react';
import PropTypes from 'prop-types';
import './ImageBlock.css';
const assetRequire = require.context('Images/howItWorks/', true, /\.(png|jpg|svg)$/);
const ImageBlock = async ({ imageSrc, alt }) => {
const imageSrc1x = assetRequire(`${imageSrc}.png`);
const imageSrc2x = assetRequire(`${imageSrc}@2x.png`);
return (
<img
src={imageSrc1x}
srcSet={`${imageSrc1x} 1x, ${imageSrc2x} 2x`}
alt={alt}
styleName="image-block"
/>
);
};
ImageBlock.propTypes = {
imageSrc: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
};
export default ImageBlock;
任何帮助将不胜感激。
答案 0 :(得分:0)
因此,在进行更多搜索之后,我在这里找到了可行的解决方案
Dynamically import images from a directory using webpack
我的重构版本低于
import React from 'react';
import PropTypes from 'prop-types';
import './ImageBlock.css';
function importAll(r) {
const images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); }); //eslint-disable-line
return images;
}
const images = importAll(require.context('Images/howItWorks/', false, /\.(png|jpe?g|svg)$/));
const ImageBlock = ({ imageSrc, alt }) => {
const imageSrc1x = images[`${imageSrc}.png`];
const imageSrc2x = images[`${imageSrc}@2x.png`];
return (
<img
src={imageSrc1x}
srcSet={`${imageSrc1x} 1x, ${imageSrc2x} 2x`}
alt={alt}
styleName="image-block"
/>
);
};
ImageBlock.propTypes = {
imageSrc: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
};
export default ImageBlock;