File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11import React from 'react' ; // 虽然也许可能没有使用,如果删了就会报错React.createElement
22import ReactDOM from 'react-dom' ;
33
4- import './test/test1'
4+ // import './test/test1'
5+ import './test/toggleImg'
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments