如何根据发送的道具渲染图像?

时间:2019-03-29 14:58:43

标签: javascript html reactjs

我是新来的反应者,目前正尝试练习一些。我制作了一个名为“ Recensie”的组件,并在其中渲染了两个组件。

在该查看组件中,我想根据我从该组件发送的图像道具来显示图像。但是我无法使它工作。目前,这是我的代码:

import React from 'react'
function Recensie(props){
    return(
        <div className="recensie">
            {console.log(props.image)}
            <img src={`../imgs/${props.name}.png`}></img>
            <hr/>
            <h2>Lorem Ipsum</h2>
            <h2>Lorem Ipsum</h2>
        </div>
    )
}

export default Recensie

主要组件代码如下:

import React from 'react'
import Recensie from './Recensie'

class Main extends React.Component{
    constructor(){
        super()
        this.state={

        }
    }

    render(){
        return(
            <div className="recensies">
                <Recensie name="one"/>
                <Recensie />
                <Recensie />
            </div>
        )
    }
}
export default Main

但是,该图像实际上并未显示: https://i.imgur.com/dbvYTqE.png

我已经看到我可以像这样导入确切的图像:

import React from 'react'
import imgs from '../imgs/one.png'

function Recensie(props){
    return(
        <div className="recensie">
            {console.log(props.image)}
            <img src={imgs}></img>
            <hr/>
            <h2>Lorem Ipsum</h2>
            <h2>Lorem Ipsum</h2>
        </div>
    )
}

export default Recensie

但是,这意味着我必须对图像进行硬编码。

有什么办法可以做我本来想做的事,还是有一种解决方法?

2 个答案:

答案 0 :(得分:0)

这是我能想到的最简单的例子:

**[XCUITest] Error: Could not install app: 'Command 'ios-deploy --id 3b5c144433dacabd74d93251d33bd2afa661be47 --bundle /var/folders/b9/sq2txlwd7b33njkgq7qgffhw0000gn/T/2019229-1728-as7h53.ceh0m/Payload/Instagram.app' exited with code 253'
[XCUITest]     at IOSDeploy.install (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/ios-deploy.js:40:13)
[XCUITest]     at process._tickCallback (internal/process/next_tick.js:68:7)
[XCUITest] Not clearing log files. Use `clearSystemFiles` capability to turn on.
[iOSLog] Stopping iOS log capture
[BaseDriver] Event 'newSessionStarted' logged at 1553871674896 (18:01:14 GMT+0300 (IDT))
[MJSONWP] Encountered internal error running command: Error: Could not install app: 'Command 'ios-deploy --id 3b5c144433dacabd34311251d33bd2afa661be47--bundle /var/folders/b9/sq2txlwd7b33njkgq7qgffhw0000gn/T/2019229-1728-as7h53.ceh0m/Payload/Instagram.app' exited with code 253'
[MJSONWP]     at IOSDeploy.install (/Applications/Appium.app/Contents/Resources/app/node_modules/appium/node_modules/appium-xcuitest-driver/lib/ios-deploy.js:40:13)
[MJSONWP]     at process._tickCallback (internal/process/next_tick.js:68:7)
[HTTP] <-- POST /wd/hub/session 500 44559 ms - 355
[HTTP] 
[HTTP] --> DELETE /wd/hub/session
[HTTP] {}
[HTTP] No route found. Setting content type to 'text/plain**

像这样使用它:

class Recensie extends React.Component {
    state = {
        image: null,
    };

    componentDidMount() {
        import("./images/" + this.props.name).then((image) => {
            this.setState({ image: image.default });
        });
    }

    render() {
        return this.state.image ? (
            <img alt="image" src={this.state.image} />
        ) : null;
    }
}

它使用动态导入,该导入是异步的(对数据的异步调用应在<Recensie name="test.png" /> 中进行,有关更多信息,请参见React docs)。

请不要忘记根据componentDidMount组件的位置正确调整图像文件夹的路径。

答案 1 :(得分:0)

我这样做。在一些utils文件夹中创建文件imageLoader.js

// imageLoader.js
// inside images object i name routes for my images from assets folder
// and export loadImage function

const images = {
  img1: require('../../assets/images/img1.jpg'),
  img2: require('../../assets/images/img2.png'),
  flagNotFound: require('../../assets/images/flag_not_found.png')
};

export function loadImage(imageName) {
  if (images.hasOwnProperty(imageName)) {
    return images[imageName];
  }
  return images['flagNotFound'];
}

使用方式

import {loadImage} from '../location-to-imageLoader'

<img alt="not found" src={loadImage('img1')}/>

以您的情况

 <img alt="not found" src={loadImage(props.name)}/>