javascript 如何通过反应中的道具导入图像并使用“导入”路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46417199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:39:15  来源:igfitidea点击:

how to import images via props in react and use the 'import' path

javascriptreactjsecmascript-6jsx

提问by Fahad Bilal

i'm passing the following as props.

我将以下内容作为道具传递。

const people=['Eliana','Stefania','Ahmed']

{
  people.map(function(name, index){
    return <Person item={index} name={name}/>;
  })
}

import Eliana from '../assets/imgs/people/eliana.png'
import Stefania from '../assets/imgs/people/stefania.png'
import Ahmed from '../assets/imgs/people/ahmed.png'

export default class Person extends React.Component {
  render() {
    return (
      <div>
        <img src={this.props.name} alt=''/>
     <li key={this.props.item}>{this.props.name}</li>
   </div>
    );
  }
}

what i'm doing here is using the above strings in the array to pass to a component and then generate images from that component by using the corresponding path, however when i pass the props, they display as strings, like Eliana would display as is in the img src?

我在这里做的是使用数组中的上述字符串传递给一个组件,然后使用相应的路径从该组件生成图像,但是当我传递道具时,它们显示为字符串,就像 Eliana 会按原样显示在 img src 中?

how do i get corresponding paths? some kind of string conversion probably? i bet this is an easy one!

我如何获得相应的路径?可能是某种字符串转换?我敢打赌这是一个简单的!

回答by Andrew

An easy fix for what you're asking about

一个简单的解决你所问的问题

<img src={require(this.props.name)} alt=''/>

But this is implying that you have the full path. What you currently have doesn't look like will work. In one way or another, each one has to end up with a path name, like this, when React interprets your code:

但这意味着您拥有完整的路径。您目前拥有的看起来不起作用。以一种或另一种方式,当 React 解释您的代码时,每个人都必须以一个路径名结束,就像这样:

<img src={require('../assets/imgs/people/ahmed.png')} alt=''/>

A simple fix is to add the path as a string before your this.props.name. It's standardized so all you have to do is add the name in, like so:

一个简单的解决方法是将路径作为字符串添加到this.props.name. 它是标准化的,所以您要做的就是添加名称,如下所示:

<img src={require(`../assets/imgs/people/${this.props.name.toLowerCase()}.png`)}/>

Be sure to document this though. You definitely want to document this.

不过一定要记录下来。你肯定想记录下来。

回答by Gage Hendy Ya Boy

You could just use concatenate the entire URL besidesthe name, then concatenate the nameprop in it's place.

除了名称之外,您可以只使用连接整个 URL ,然后name在它的位置连接道具。

<img src={require('../assets/imgs/people/' + this.props.name + '.png')}