我在这里问了一个问题How to join an array with folder images in React,但没有得到任何帮助。所以我试图改变逻辑,不幸的是没用。我有一个带有数组的父组件。这个子组件应该渲染该数组并以某种方式从本地文件夹渲染图像。文件夹名称等于 project.image。
子组件
export default class Child extends Component {
render() {
const { project } = this.props;
function importAll(r) {
return r.keys().map(r);
}
const folder1 = importAll(require.context('../../assets/images/folder1',false,/\.(png|jpe?g|svg)$/));
const folder2 = importAll(require.context('../../assets/images/folder2',false,/\.(png|jpe?g|svg)$/));
return (
<div className="portfolio-item">
<div className="desc">
<div className="item-name">
<p>{project.name}</p>
</div>
<div className="image-block">
<div className="item-images">
<Carousel showArrows={true} showThumbs={false} >
// 尝试 1(这很好用,但它是 hurdcoded ......所以它不是一个解决方案)
{project.image === 'folder1' ? folder1.map((image, index) => {
return (
<div className="image-block-small" key={index}>
<div>
<img src={image} alt=""/>
</div>
</div>
)})
: null}
</Carousel>
</div>
// 尝试 2(这里 project.image 等于 folder1(文件夹名称),但在这里我得到错误“TypeError: webpack_require (...).context is not a function”,因为传递给 require.context 的参数必须是文字! )
{importAll(require.context('../../assets/images/' + project.image, false, /\.(png|jpe?g|svg)$/)).map((image, index) => {
return (
<div className="image-block-small" key={index}>
<div>
<img src={image} alt=""/>
</div>
</div>
)})
: null}
</Carousel>
</div>
我什至试图让它像一个变量
const folder1 = '../../assets/images/folder1';
{importAll(require.context(folder1, false, /\.(png|jpe?g|svg)$/)).map((image, index) => { ... }
但得到了与第二次尝试相同的响应。任何帮助将不胜感激。