业务系统中会有一些对附件的展示功能,比如文档或者图片之类,要么能下载,要么能预览,二者定有一条途径可以看到附件内容。
文档类多以链接+文件名的形式展示,点击文件名可以下载文件。
图片也可以以这种方式展示,也可以进行预览,这种方式会更加直观。
控件会需要一个左右翻页效果的两个按钮,当图片数量超过4时可以左右翻页,下载类、预览类分开处理。
AttachComponent.tsx
interface IProps{ attachData:any;}function AttachComponent(props:IProps):JSX.Element{ const {attachData} = props; cosnt [imgList,setImgList] = useState([]); const [docList,setDocList] = useState([]); const [current,setCurrent] = useState(0); // use variable 'current' set current img index const [moveWidth,setMoveWidth] = useState(0); useEffect(()=>{ handleAttachData(); },[attachData]) useEffect(()=>{ handleMove(); },[current]); const handleAttachData =() =>{ const ImgArr :any = []; const DocArr :any = []; attachData.forEach((item:any=>{ cosnt {type} = item; // distinguish image and doc by type if(1 === type){ ImgArr.push(item); }else if(2 === type){ DocArr.push(item); } })) setImgList(ImgArr); setDocList(DocArr);}const handleMove =() =>{ setMoveWidth( current * 100 );}// handle page left const HandleMoveLeft = () =>{ setCurrent(current -1 > 0 ? current -1 : 0);}// handle page rightconst HandleMoveRight = () =>{ let maxCnt = parseInt((imgList.length / 4).toString()); if(imgList.length % 4 ){ maxCnt = maxCnt + 1; } if(current +1 >= maxCnt){ return; } setCurrent(current + 1 );}return( <div className = 'attach-container'> {docList.length >0 && <ul className = 'doc-list'> { docList.map((item:any,index:number)=>{ return <li className = 'doc-item' key = {`doc-item-${index}`}><a href ={'doc file url for download'} download ={true}>{item.name}</a></li> }) } </ul> } {imgList.length > 0 && <div className = 'img-list'> <div className = 'img-container'> { imgList.map((item:any,index:number)=>{ return <div key={`doc-item-${index}`} className ='img-item'><img src = {'img file url for download'} alt='load file failed'/></div> }) } </div> // when length >4 show page left btn { imgList.length > 4 && <div className = 'left' onClick={handleMoveLeft}> <img src={'left button src'} alt ='picture load failed'/> </div> } { imgList.length > 4 && <div className = 'right' onClick={handleMoveRight}> <img src={'right button src'} alt ='picture load failed'/> </div> } </div> } </div> )}export default Memo(AttachComponent);
AttachComponent.less
.attach-container{ width:100%; position:relative; .img-list{ width:100%; position:relative; padding:.1rem 0; .img-container{ position:relative; left:0; transition:left 0.3s; } .img-item{ display:inline-block; width:23.5%; margin-left:2%; height:1.3rem; img{ width:100%; height:100%; } &:nth-of-type(1){ margin-left:0; } &:nth-of-type(5n){ margin-left:0; } } } .left, .right{ width:.5rem; height:.5rem; background:rgba(0,0,0,0.3); border-raidus:50%; position:absolute; display:flex; justify-content:center; align-items:center; } .right{ right:0; } ul,li{ margin:0; padding:0; a{ #427aff; } }}