需求:鼠标mouseover上图片,自动切换为对应的大图片。
import React,{useState} from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function ChangePicpath(props){ const [lists,setList]=useState(props.lists); const [listsBig,setBig]=useState(props.listsBig); const [isComplete,setComplete]=useState(false); const [imgBig,setimgBig]=useState('./img/02/big_1.jpg'); const handleOver=function(index){ var img=new Image(); img.src=listsBig[index].src; setimgBig(listsBig[index].src); setComplete(true); img.complete ? setComplete(false) : handleLoad(); }; const handleLoad=function(){ setComplete(false); }; return( <ul id="box"> <li className='first'><img alt="money" onLoad={()=>handleLoad} src={imgBig}/><div className={isComplete ? 'current' : ''}></div></li> {lists.map((item,index)=> <li key={index}> <a href="#"> <img alt="money" src={item.src} onMouseOver={()=>handleOver(index)}/> </a> </li> )} </ul> ) } const lists=[ {src:require('./img/02/small_1.jpg')}, {src:require('./img/02/small_2.jpg')}, {src:require('./img/02/small_3.jpg')}, {src:require('./img/02/small_4.jpg')}, {src:require('./img/02/small_5.jpg')}, {src:require('./img/02/small_6.jpg')}, {src:require('./img/02/small_7.jpg')}, {src:require('./img/02/small_8.jpg')}, {src:require('./img/02/small_9.jpg')}, {src:require('./img/02/small_10.jpg')}, {src:require('./img/02/small_11.jpg')} ]; const listsBig=[ {src:require('./img/02/big_1.jpg')}, {src:require('./img/02/big_2.jpg')}, {src:require('./img/02/big_3.jpg')}, {src:require('./img/02/big_4.jpg')}, {src:require('./img/02/big_5.jpg')}, {src:require('./img/02/big_6.jpg')}, {src:require('./img/02/big_7.jpg')}, {src:require('./img/02/big_8.jpg')}, {src:require('./img/02/big_9.jpg')}, {src:require('./img/02/big_10.jpg')}, {src:require('./img/02/big_11.jpg')} ]; ReactDOM.render( <ChangePicpath lists={lists} listsBig={listsBig} />, document.getElementById('root') )