首页 > 解决方案 > 图像不可见(来源无法识别)

问题描述

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

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

你能帮忙吗?

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;

标签: javascriptimagereactjsinfinite-scroll

解决方案


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

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

...

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

推荐阅读