【问题标题】:Passing an image to a react.js component将图像传递给 react.js 组件
【发布时间】:2019-06-09 14:50:23
【问题描述】:

我正在创建一个网站,我想将一个图像 url 传递给一个组件。 我该怎么做?

我试过了:

App.js:

    import React from 'react';
    import './App.css';

    import Elem from './Elem.js';

    const App = () => {

      return (

          <Prod imgUrl="../../url/to/img.png"/>

        </div>
      );
    }

    export default App;

Elem.js:

    import React from 'react';
    import './Elem.css';

    const Prod = ({imgUrl}) => {
        return (
            <div className="elem">
                <div className="elemImg">
                    <img src={require(`${imgUrl}`)} alt="" />
                </div>
            </div>
        );
    }

    export default Elem;

但它给了我错误:

错误:找不到模块'../../url/to/img.png'

【问题讨论】:

  • 路径正确。

标签: reactjs


【解决方案1】:

我建议导入图片而不是直接使用路径。

import myImage from 'path/to/image.png'

const App = () => <ImageComponent src={myImage} />

const ImageComponent = props => <img src={props.src} />

如果您真的想直接使用路径,我建议您从入口点调整路径。

假设您的入口点是index.html,您的相对路径应该基于该文件而不是来自JS 文件。

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多