主流modal大多須要在組件內使用state控制是否顯示,在多個地方調用的時候很不方便,因此基於 context 提供一個更加易用的調用方式。html
use-modal
支持主流的modal, 理論上只要modal經過相似於 show props
控制顯示的,就能夠支持,例如:react
源碼地址: github.com/wowlusitong…git
使用yarngithub
$ yarn add react-use-modal
複製代碼
或者用npmnpm
$ npm install react-use-modal --save
複製代碼
將 ModalProvider
放在組件外層bootstrap
import ReactDOM from 'react-dom';
import { ModalProvider } from 'react-use-modal';
ReactDOM.render(
<ModalProvider> ... </ModalProvider>,
document.querySelector('#root')
)
複製代碼
調用方式,以react-bootstrap舉例api
使用contextbash
import React from 'react';
import { Modal } from 'react-bootstrap';
import { ModalContext } from 'react-use-modal';
export default class App extends React.Component {
handleClick = () => {
const {showModal, closeModal} = this.context;
showModal(({ show }) => (
<Modal show={show} onHide={closeModal}> <Modal.Body>body</Modal.Body> </Modal> )) } render() { return ( <button onClick={this.handleClick}>click</button> ) } } Product.contextType = ModalContext 複製代碼
使用hooksantd
import React from 'react';
import { Modal } from 'react-bootstrap';
import { useModal } from 'react-use-modal';
const App = () => {
const { showModal, closeModal } = useModal();
function handleClick() {
showModal(({ show }) => (
<Modal show={show} onHide={closeModal}>
<Modal.Header closeButton>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>Modal body text goes here.</Modal.Body>
</Modal>
))
}
return (
<button onClick={handleClick}>modal</button>
)
}
複製代碼
顯示modal,將 show
設置爲truedom
component(?Function): 第一次調用必須傳遞參數,再次調用可忽略
showModal(props => (
<Modal show={show} onHide={closeModal}> <Modal.Body>body</Modal.Body> </Modal> )) 複製代碼
組件props
Name | Type | Default | Description |
---|---|---|---|
show | boolean | false | 是否顯示modal |
關閉modal,將 show
設置爲false