跳到主要内容

ant-design-image

2023年03月06日
柏拉文
越努力,越幸运

一、认识


AntDesignImage

二、语法


2.1 封装

import React, {useState} from 'react';
import {Image} from 'antd';

interface AntDesignImagePropsType {
src: string;
previewList?: string[];
}

function AntDesignImage(props: AntDesignImagePropsType) {
const {src, previewList} = props;
const [visible, setVisible] = useState(false);

const getCurrentIndex = () => {
if (previewList && previewList.length) {
return previewList.indexOf(src);
}
return 0;
};
const renderPreview = () => {
if (previewList && previewList.length) {
return (
<>
{previewList.map((item, index) => {
return <Image key={index} src={item} />;
})}
</>
);
}
return <Image src={src} />;
};

return (
<>
<Image
preview={{visible: false}}
src={src}
onClick={() => setVisible(true)}
/>
<div style={{display: 'none'}}>
<Image.PreviewGroup
preview={{
visible,
current: getCurrentIndex(),
onVisibleChange: (vis) => setVisible(vis),
}}>
{renderPreview()}
</Image.PreviewGroup>
</div>
</>
);
}

export default AntDesignImage;

2.2 使用

import './App.css';
import React from 'react';
import AntDesignImage from './components/antDesignImage';

import bg1 from './bg1.jpg';
import bg2 from './bg2.jpg';
import bg3 from './bg3.jpg';

function App() {
const previewList = [bg1, bg2, bg3];
return (
<div className="App">
<div className="img-wrap">
<AntDesignImage src={bg1} />
</div>
<div className="img-wrap">
<AntDesignImage src={bg2} previewList={previewList} />
</div>
<div className="img-wrap">
<AntDesignImage src={bg3} previewList={previewList} />
</div>
</div>
);
}

export default App;