React.js传递路径作为道具

时间:2018-08-25 06:44:43

标签: javascript reactjs frontend

我试图将路径值作为React.js中的属性传递到我的图片文件夹。这是我的做法:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function importAll(r) {
    let images = [];
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

class CoverGallery extends React.Component {
   
    constructor(props) {
        super(props);
    }

    renderImgs() {
        console.log(this.props.location);
        const images = importAll(require.context(this.props.location, false, /\.(png|jpe?g|svg)$/));      
        console.log(images);
        let imagearray = [];
        for(var key in images) {            
            imagearray.push(<img key={key} className="galery" src={images[key]} alt="Description of the universe" ></img>);
        }
        return <div>{imagearray}</div>
    }

    render() {

        return (
            <div className="photo-gallery">
                {this.renderImgs()}
            </div>
        )
    }
}

class Blog extends React.Component {
    render() {
        return (
            <CoverGallery location="../pictures/"/>
        )
    }
}

ReactDOM.render(
    <Blog />,
     document.getElementById('root')
);

如果我在renderImgs()中将this.props.location替换为“ ../pictures/”,则一切正常。

此行为背后的原因是什么,以及如何解决此问题?

谢谢!

编辑: 我要尝试的是使用特定文件夹位置中的所有图像进行幻灯片显示。好的旧的“从y导入x”是不合适的,因为我不知道预先的确切图像计数。

因此,我正在使用Webpack来做到这一点。如何绕过Webpack的要求才能提前知道确切的文件夹位置?

0 个答案:

没有答案
相关问题