Skip to content

Commit ce763e4

Browse files
committed
feat: toggleImg test
1 parent f782a63 commit ce763e4

4 files changed

Lines changed: 58 additions & 1 deletion

File tree

Lines changed: 3 additions & 0 deletions
Loading
Lines changed: 3 additions & 0 deletions
Loading

React/sandboxs/src/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import React from 'react'; // 虽然也许可能没有使用,如果删了就会报错React.createElement
22
import ReactDOM from 'react-dom';
33

4-
import './test/test1'
4+
// import './test/test1'
5+
import './test/toggleImg'
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import React from "react";
2+
import ReactDOM from 'react-dom';
3+
// 作为模块导入资源而不是拼接路径,否则打包后出问题
4+
import img1 from '../assets/ceilf6.png'
5+
import img2 from '../assets/maqima.jpeg'
6+
7+
const imgs = [img1, img2]
8+
9+
let index = 0; //显示的图片索引
10+
11+
const container = document.getElementById('root');
12+
13+
let timer; //计时器
14+
15+
/**
16+
* 根据index的值,显示某张图片
17+
*/
18+
function render() {
19+
ReactDOM.render(<img src={imgs[index]} alt="" />, container);
20+
}
21+
22+
/**
23+
* 启动计时器,每隔一段时间,切换图片
24+
*/
25+
function start() {
26+
stop();
27+
timer = setInterval(() => {
28+
index = (index + 1) % 3; //改变index
29+
render(); // 每次都需要重新构建React元素对象
30+
}, 2000);
31+
}
32+
33+
/**
34+
* 停止计时器
35+
*/
36+
function stop() {
37+
clearInterval(timer);
38+
}
39+
40+
render();
41+
42+
start();
43+
44+
container.onmouseenter = function () {
45+
stop();
46+
}
47+
48+
container.onmouseleave = function () {
49+
start();
50+
}

0 commit comments

Comments
 (0)