Import image dynamically in React component

我只是一个虾纸丫 提交于 2020-12-29 10:31:30

问题


I have an Articles component that shows a blog page with listed articles.

render() {
    const articles = {
        ...this.state.articles
    }

    const article = Object.keys(articles).map(cur => {
        return <Article
            key={this.state.articles[cur].id}
            imgName={this.state.articles[cur].thumb}
            title={this.state.articles[cur].title}
            meta={this.state.articles[cur].meta}
            clicked={() => this.detailedHandler(this.state.articles[cur].id)}
            detailed={this.state.articles[cur].detailed} />
    });

As you can see I pass image name with props to Article component. I want then to display the appropriate image for each article.

How do I import an image in Article component based on the props I receive (props.imgName) from Articles component?


回答1:


I used context.

const images = require.context('../../../assets/img', true);
let img = images('./' + props.imageName);
<img src={img} alt="" />

I don't know if this is an optimal solution, but it works.




回答2:


You can load images dynamically from the API response with dynamic imports that is Stage 3 proposal as of now.

The resulting code should look something like:

loadImage = imageName => {
  import(`./assets/${imageName}.jpg`).then(image => {
    this.setState({
      image
    });
  });
};
render() {
  const { image } = this.state;
  return (
    <Fragment>
      {image && <img src={image} alt="" />}
    </Fragment>
  );
}

View Codesandbox Demo

This feature is supported out of the box in create-react-app, If using other systems, you can use the Babel plugin



来源:https://stackoverflow.com/questions/53775936/import-image-dynamically-in-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!