javascript - 图像不可见(来源无法识别)
问题描述
我正在 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;
解决方案
您必须使用 require 或 import 获取图像,然后在 src 中使用它,
const image = require("../resources/Photos/1.jpg")
...
items.push(<img src={image}></img>);
推荐阅读
- laravel - 用于 camelCase 属性的 Laravel 访问器
- c# - CSharp 代码生成器给出 System.PlatformNotSupportedException
- api - 物联网云服务器 P2P
- python - 对重新排序 Dict 或 OrderedDict 的能力感到困惑
- git - 无法使用 Sourcetree 克隆存储库
- cloud-foundry - CF 市场未找到服务产品
- prolog - maplist 仅适用于列表列表的第一个列表?
- javascript - 我应该使用 Python 还是 Javascript 来使用 Django 构建基于文本的冒险?
- r - 在ggplot 2中的x轴上将时间从几分钟缩放到几小时
- swift - 在 SwiftUI Document App 中,如何从函数中保存文档