麻烦的 Modal
在 React 下面使用 Modal 是很麻烦的,比如下面这个 antd 的 Modal:
const DemoModal: React.FC = ({
isModalVisible,
setIsModalVisible,
onChange,
otherProps
}) => {
const handleOk = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
};
return (
Some contents...
);
};
单单一个 Modal 是没什么用的,一般会在父组件中的某个事件里触发,弹出窗口,一顿操作后返回些数据。
const App: React.FC = () => {
const [isModalVisible, setIsModalVisible] = useState(false);
const [others, setOthers] = useState(null);
const showModal = () => {
setIsModalVisible(true);
};
return (
<>
Open Modal
>
);
};
那么以下这些情况也就不得不面对:
很多情况下 isModalVisible 和 setIsModalVisible 需要从父组件传递下来(比如说某个操作触发 Modal 显示/隐藏);
还需要一个 onChange 还有来接受 Modal 中传递的数据;
还有一些 otherProps 来给 Modal 传递数据;
一个 Modal 就要添加这么多 state、callback,那么如果有很多个呢?
还有一点是,父组件其实完全不关心 Modal 的状态,它只是需要 Modal 返回的一个结果。我为什么要维护这些个 state、callback?
解决方案
nice-modal-react
nice modal react 这个库可以解决上面的问题,具体的 demo 可以官网看。
在调用者视角,它只用传递好参数,等着返回结果就行:
import NiceModal from '@ebay/nice-modal-react';
import MyAntdModal from './my-antd-modal'; // created by above code
function App() {
const showAntdModal = () => {
// Show a modal with arguments passed to the component as props
NiceModal.show(MyAntdModal, { name: 'Nate' }).then(res => {
// do something
console.log(res);
});
};
return (
Nice Modal Examples
Antd Modal
);
}
它的好处有:
不用到处声明 Modal
父组件不用维护额外的状态(Modal是非受控的)
基于 Promise 调用 Modal