【发布时间】:2018-06-02 13:37:57
【问题描述】:
我正在用 React.js 制作一个简单的网络应用程序(+ Spring in back)。
我在函数 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;
【问题讨论】:
-
您的一般方法看起来不错。你能在浏览器的调试器中查看 img 标签在页面上时的 HTML 是什么吗?这是一个演示示例:codesandbox.io/s/5yrvrvl7lx
-
我认为问题出在图片的位置。您将它们与没有
importing 或requireing 的相对路径一起使用。然后编译器不知道它应该将它们添加到根包中。您可以尝试移动到您的公共文件夹。 -
谢谢,你很聪明。你知道为什么:const image = require("../resources/Photos/1.jpg"),但是 const image = require("../resources/Photos/" + i + ".jpg); 不?
标签: javascript image reactjs infinite-scroll