然后我们来看下使用React Hooks怎么实现一个自定义的Modal组件。
export const useModal = (initTitle: string, initContent: string | React.ReactElement) => {
const [visible, setVisible] = useState(false);
const [title, setTitle] = useState(initTitle);
const [content, setContent] = useState(initContent);
const CustomModal = () => {
return (
<Modal
visible={visible}
title={title}
closable={false}
footer={null}
>
{content}
</Modal>
);
}
const show = (content?: string | React.ReactElement) => {
content && setContent(content);
setVisible(true);
};
const hide = (delay?: number) => {
if (delay) {
setTimeout(() => setVisible(false), delay);
} else {
setVisible(false)
}
};
return {
show, hide, CustomModal, setTitle, setContent
}
}
使用:
const {hide, show, CustomModal} = useModal('系统提示', '正在初始化...');
render() {
<div><CustomModal /></div>
}
网友评论