图像不可见(无法识别来源)

IT技术 javascript image reactjs infinite-scroll
2021-04-30 13:11:31

我正在 React.js 中制作一个简单的 web 应用程序(+ Spring 在后面)。

我在函数displayItems 中从本地路径显示照片 (.img) 时遇到问题图片不可见。如果我以相同的代码(src="http ......")从网络加载文件,一切都很好。

你能帮忙吗?

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个回答

您必须使用 require 或 import 获取图像,然后在 src 中使用它,

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

...

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