1.0.5 • Published 4 years ago
inject-modal v1.0.5
injectModal
Make Modal Components out of your React Component.
A middleware used to maintenance visible property
Why need injectModal
When we write a project based on React, sometimes we might meet the requirements with too many Modals,and some Modals between different page are same, but the code reuse of these Modals are difficult.
So the question is: 1. How to produce lesser visible property in my current Component? 2. How to reduce coupling and achieve code reusability?
We got the problem's solution is injectModal
, don't need put the logic about modal and a lot of visible
states in your current Component.
Useage
There have two modals ModalA and ModalB
ModalA
import React from 'react'
export const ModalA = ({visible, closeMyself, useWithOpen, ...customProps}) => {
useWithOpen(() => {
// executed after this Modal has been opened.
})
const handleModalOk = () => {
// ..some codes
}
const handleCancel = () => {
closeMyself()
}
return (
<Modal
visible = {visible}
onOk = {handleModalOk}
onCancel = {handleCancel}
>
{/*contentA*/}
</Modal>
)
}
ModalB
import React from 'react'
export class ModalB extends React.PureComponent {
constructor(props) {
super(props)
const { useWithOpen } = props
this.componentDidOpen = useWithOpen(this.componentDidOpen.bind(this))
}
componentDidOpen() {
// executed after this Modal has been opened.
}
handleModalOk = () => {
// ..some codes
}
handleCancel = () => {
const {closeMyself} = this.props
closeMyself()
}
render() {
const {visible, closeMyself, useWithOpen, ...customProps} = this.props
return (
<Modal
visible={visible}
onOk={this.handleModalOk}
onCancel={this.handleCancel}
>
{/*contentB*/}
</Modal>
)
}
}
inject ModalA and ModalB to Component
Function Component
import React from 'react' import injectModal from 'injectModal' import {ModalA} from './ModalA' import {ModalB} from './ModalB' const Components = ({modalBag}) => { const handleOpenAThenClose = () => { const modalA = modalBag.get(ModalA) modalA.open({ // customProps }).then(() => { setTimeout(() => { modalA.close() }, 3000) }) } const handleOpenB = () => { modalBag.get(ModalB).open({ // customProps }) } return ( <> <button onClick={handleOpenAThenClose}>openA then close</button> <button onClick={handleOpenB}>openB</button> </> ) } export default injectModal(ModalA, ModalB)(Components)
class Component
import React from 'react' import injectModal from 'injectModal' import {ModalA} from './ModalA' import {ModalB} from './ModalB' @injectModal(ModalA, ModalB) class Component extends React.pureComponent { ... }
You can also inject multiple Modals
injectModal(ModalA, ModalB, ModalC, ...)