返回
React 模态框组件 react-modal 的详细介绍
前端
2024-01-26 01:30:23
1. 安装
npm install react-modal
2. 导入
import ReactModal from 'react-modal';
3. 使用
const MyModal = () => {
const [showModal, setShowModal] = useState(false);
const handleOpenModal = () => {
setShowModal(true);
};
const handleCloseModal = () => {
setShowModal(false);
};
return (
<div>
<button onClick={handleOpenModal}>Open Modal</button>
<ReactModal
isOpen={showModal}
onRequestClose={handleCloseModal}
style={{
overlay: {
backgroundColor: 'rgba(0, 0, 0, 0.5)',
zIndex: 999,
},
content: {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '500px',
height: '500px',
backgroundColor: 'white',
borderRadius: '5px',
},
}}
>
<h2>Modal Title</h2>
<p>Modal Content</p>
<button onClick={handleCloseModal}>Close Modal</button>
</ReactModal>
</div>
);
};
4. 配置参数
react-modal 组件提供了丰富的配置参数,您可以根据需要进行设置。
参数 | 类型 | 默认值 | |
---|---|---|---|
isOpen | boolean | false | 是否打开模态框 |
onRequestClose | function | null | 当用户尝试关闭模态框时触发的函数 |
style | object | {} | 模态框的样式 |
overlayClassName | string | null | 模态框覆盖层的类名 |
contentClassName | string | null | 模态框内容的类名 |
ariaHideApp | boolean | true | 是否在模态框打开时隐藏应用程序 |
shouldFocusAfterRender | boolean | true | 是否在模态框渲染后将焦点设置到第一个可聚焦元素上 |
shouldCloseOnOverlayClick | boolean | true | 是否在点击模态框覆盖层时关闭模态框 |
shouldCloseOnEsc | boolean | true | 是否在按 ESC 键时关闭模态框 |
shouldReturnFocusAfterClose | boolean | true | 是否在模态框关闭后将焦点返回到之前的元素上 |
aria | object | null | ARIA 属性 |
bodyOpenClassName | string | null | 当模态框打开时添加到 body 元素的类名 |
5. 示例
您可以使用 react-modal 组件构建各种类型的模态框。以下是一些示例:
- 对话框
- 弹出窗口
- 提示框
- 加载框
- 登录框
- 注册框
6. 总结
react-modal 组件是一个功能强大的 React 库,可以帮助您轻松构建各种类型的模态框。它提供了丰富的配置参数,可以满足您的各种需求。希望本指南对您有所帮助。