hooks自定义

然后我们来看下使用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 (
visible={visible}
title={title}
closable={false}
footer={null}
>
{content}

);
}
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() {


}

你可能感兴趣的:(hooks自定义)