Image is not visible (source is not recognized)

喜夏-厌秋 提交于 2019-12-24 07:49:48

问题


I'm making a simple web-app in React.js (+ Spring in back).

I have problem with displaying a photo (.img) from local path in function displayItems. Picture is not visible. If i load file from web in the same code (src="http.......") everything is fine.

Could you help?

import React, { Component } from 'react';
import '../index.css';

class Author extends Component {

constructor(props) {
    super(props);
    this.state = {
        mail: window.location.href.slice(32, -7),
        items: 2,
        loadingState: false
    };
    this.handleChange = this.handleChange.bind(this);
}

componentDidMount() {
    this.refs.iScroll.addEventListener("scroll", () => {
        if (this.refs.iScroll.scrollTop + this.refs.iScroll.clientHeight >=this.refs.iScroll.scrollHeight){
            this.loadMoreItems();
        }
    });

}

displayItems() {
    var items = [];
    for (let i = 0; i < this.state.items; i++) {
        //PROBLEM
        items.push(<img src="../resources/Photos/1.jpg"></img>);
    }
    return items;
}

loadMoreItems() {
    this.setState({ loadingState: true });
    setTimeout(() => {
        this.setState({ items: this.state.items + 2, loadingState: false });
    }, 3000);
}

render() {
    return (
          <div
              className="vc"
              ref="iScroll"
              style={{ height: "200px", overflow: "auto" }}
          >
              <h2>My adventures: </h2>
              <div>
                  {this.displayItems()}
              </div>
              {this.state.loadingState
              ? <p className="loading">
              loading More Images..
              </p>
              : ""}
          </div>
    );
}
}
export default Author;

回答1:


You will have to get the image using require or import and then use it in the src,

const image = require("../resources/Photos/1.jpg")

...

items.push(<img src={image}></img>);


来源:https://stackoverflow.com/questions/50652239/image-is-not-visible-source-is-not-recognized

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