【问题标题】:Dynamic Image not rendering动态图像未渲染
【发布时间】:2021-01-20 19:27:08
【问题描述】:

我想动态渲染图像,但没有显示任何内容。这是我从Import image dynamically in React component 使用的起始代码。

import React, { Component, Fragment } from 'react';

class Test extends Component{
    constructor(props){
        super(props);
        this.state = {
            image: "",
        }
        this.loadImage = this.loadImage.bind(this);
    }
    componentDidMount(){
        this.loadImage("Test")
    }
    loadImage = imageName => {
        import(`../assets/${imageName}.png`).then(image => {
          this.setState({
            image
          });
        });
      };
      render() {
        const { image } = this.state;
        return (
          <Fragment>
              hello
            {image && <img src={image} alt="" />}
          </Fragment>
        );
      }
}

export default Test;

你好渲染,但图像在哪里看不到。有什么想法

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以将字符串直接添加到图像状态中,而无需异步渲染。我认为不需要导入声明。获得字符串后,您可以使用图像中已有的类似逻辑,但如果您使用的是 webpack,这可能会起作用:

    <div
        style={{
          backgroundImage: `url(${image})`,
          height: "106px"
        }}

    如果你没有使用 webpack,那么你可以在 src 属性中添加图片状态。

    【讨论】:

    • 我是新手,正在使用 create-react-app。我以前使用过您发布的解决方案,但它对我不起作用。但是,只有当我将样式放在相应的 css 文件中时,图像才会渲染。 URL 显然是静态的。我不确定我做错了什么。我要显示图像的唯一方法是在文件顶部使用 import x from "../test.png"(示例),您可以在其中使用其他导入语句。你知道我在这里做错了什么吗?
    • 如果你导入的是静态资源,你就做对了,动态资源有点棘手,特别是如果你使用 webpack 会强制开发人员在 img src 属性中使用 require('./img')加载图像。通过 css 渲染图像是处理动态图像最简单的方法。
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 2017-01-04
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多