javascript - 同时加载多个图像
问题描述
我正在尝试在 React.js 中同时加载图像。
我尝试了很多,但仍然无法弄清楚,该怎么做。
- 这是第一件事,我尝试正常加载图像。
class MultipleImageExample extends React.Component {
constructor(props) {
super(props);
this.state = {
imageOneUrl: `https://picsum.photos/id/${parseInt(
Math.random() * 1000,
10
)}/400.jpg`,
imageTwoUrl: `https://picsum.photos/id/${parseInt(
Math.random() * 1000,
10
)}/400.jpg`,
imageOneLoaded: false,
imageTwoLoaded: false
};
}
render() {
return ( <
div >
<
h1 > Multiple Image Example < /h1> <
img src = {
this.state.imageOneUrl
}
style = {
{
objectFit: "cover",
width: "312px",
height: "216px"
}
}
alt = "image1" /
>
<
img src = {
this.state.imageTwoUrl
}
style = {
{
objectFit: "cover",
width: "312px",
height: "216px"
}
}
alt = "image2" /
>
<
/div>
);
}
}
ReactDOM.render( < MultipleImageExample / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
- 这是加载事件,我已附加到 img 标签。
class MultipleImageExample extends React.Component {
constructor(props) {
super(props);
this.state = {
imageOneUrl: `https://picsum.photos/id/${parseInt(
Math.random() * 1000,
10
)}/400.jpg`,
imageTwoUrl: `https://picsum.photos/id/${parseInt(
Math.random() * 1000,
10
)}/400.jpg`,
imageOneLoaded: false,
imageTwoLoaded: false
};
}
handleImage1Load = e => {
this.setState({ ...this.state, imageOneLoaded: true });
};
handleImage2Load = e => {
this.setState({ ...this.state, imageTwoLoaded: true });
};
render() {
return (
<div>
<h1>Multiple Image Example</h1>
<img
src={this.state.imageOneUrl}
style={{ objectFit: "cover", width: "312px", height: "216px" }}
alt="image1"
onLoad={this.handleImage1Load}
/>
<img
src={this.state.imageTwoUrl}
style={{ objectFit: "cover", width: "312px", height: "216px" }}
alt="image2"
onLoad={this.handleImage2Load}
/>
</div>
);
}
}
ReactDOM.render(<MultipleImageExample />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
我仍然很困惑,如何将加载的图像一起显示。
请帮助解决这个问题。这是沙盒链接:https ://codesandbox.io/s/react-example-5f71p
解决方案
您可以使用第二种方法,并隐藏图像,直到另一个图像加载完毕,这是一个有效的沙箱链接(基于您的链接):https ://codesandbox.io/s/react-example-3iblh
例如,对于第一张图片,您可以根据状态处理可见性:
visiblity: this.state.imageTwoLoaded ? "visible" : "hidden"
推荐阅读
- java - Java中的#define指令
- python - 使用 PySerial 与 Arduino 通信,如何告诉 Python 在接收到某些输入后只执行一次函数?
- c++ - 循环未正确处理“\n”比较
- javascript - 无法在 React Web App 中导入 css 文件
- kubernetes - 如何在 Kubernetes 清单中进行变量替换?
- javascript - 如何使用 CSS(少)
- python-3.x - OrderedDict 的抽象子类?蟒蛇3
- azure - 如何从 Azure DevOps 管道向 azure key Vault 写入机密?
- r - R中createDataPartition的y值
- javascript - 如何在js中修剪html内容?