前言
上篇實(shí)現(xiàn)了一個(gè)Ant Model的封裝方案,雖然能work,但代碼有點(diǎn)丑不夠美觀蒲犬。本篇結(jié)合了React的高階組件特性陨收,傳入一個(gè)Form類即可創(chuàng)建一個(gè)Modal類。現(xiàn)在做如下陳述没佑。
示意圖
解釋如下
- createModal為一個(gè)高階函數(shù)(也稱高階組件)毕贼,傳入一個(gè)Form類,獲得一個(gè)Modal類蛤奢,接受和返回的對(duì)象類似于Java里的Class類
- Modal類的創(chuàng)建過程中并沒有定義Form,因此它會(huì)直接使用createModal里的Form鬼癣。
- 這樣傳入一個(gè)LoginForm,就可獲得LoginModal.
-
LoginModal在實(shí)例化時(shí),需要傳入props啤贩,包括hint(在主頁面上的提示)和title(對(duì)話框的標(biāo)題,也稱caption)
示意圖
代碼
只貼出createModal的代碼
const createModal= SubComponent =>class extends React.Component {
state = {
visible: false,
}
showModal = (e)=>{
this.setState({visible:true})
}
handleClose = ()=>{
this.setState({visible:false})
}
renderAnchor = (hint, anchor)=>{
if(anchor=='button') {
return <Button type='primary' onClick={this.showModal}>
{hint}
</Button>
}
return <span style={{ color :'blue'}} onClick={this.showModal}>
{hint}
</span>
}
render() {
const {hint, title, anchor, ...rest} = this.props
return (
<span>
{this.renderAnchor(hint, anchor)}
<Modal title={title} visible={this.state.visible}
footer={null}
onOk={this.handleClose}
onCancel={this.handleClose}>
<SubComponent onSubmit={this.handleClose} {...rest}/>
</Modal>
</span>
)
}
}
export default createModal
調(diào)用示例
RegisterForm是需要用Modal包裝的組件
const RegisterComponent=createModal(RegisterForm)
const RegisterModal = ({hint='注冊(cè)',title='請(qǐng)注冊(cè)',anchor='span'})=>{
return <RegisterComponent hint={hint} title={title} anchor={anchor}/>
}