本教程操作环境:windows10系统、react17.0.1版、dell g3电脑。
react中modal的用法是什么modal 简述
模态对话框。需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 modal 在当前页面正中打开一个浮层,承载相应的操作。
另外当需要一个简洁的确认框询问用户时,可以使用 modal.confirm() 等语法糖方法。
核心功能点提取
根据 antd modal 文档提供的接口来实现 modal.
核心实现
modal 组件的特殊在于它有两种用法:
通常用法:<modal visible={this.state.visible} {...props}></modal>调用静态方法: modal.confirm({ title: '取消后,已编辑的脚本信息将不会保存,请确认是否取消。', oktext: '确认取消', canceltext: '暂不取消', onok() { me.props.oncancel(); } })我的想法是这两种调用都在internalmodal.tsx中统一维护
顺着这个思路, 对于 modal.tsx 。
1)不会维护 render 方法, 而是在 componentdidmount / componentdidupdate 生命周期中调用 internalmodal.tsx 完成渲染
2)modal.tsx 中维护相关静态方法 confirm, error, info 等。
// modal.tsxexport default class modal extends react.component<modalprops, {}> { static proptypes = { ... }; static confirm(content) { const modal = new internalmodal(); const props = { ...modal.defaultprops, title: '提示', children: content, cancelbutton: true, okbutton: true, okbuttontext: '确定', cancelbuttontext: '取消', closable: false, visible: true, onok() { modal.destroy(); }, oncancel() { modal.destroy(); } }; modal.render(props); } private modal; constructor(props: modalprops) { super(props); this.modal = new internalmodal(); } componentwillunmount() { this.modal.destory(); this.modal = null; } componentdidmount() { this.modal.render(this.props); } componentdidupdate() { this.modal.render(this.props); } componentwillreceiveprops(nextprops) { if (nextprops.visible) { this.modal.show(); } else { this.modal.hide(); } } render() { return null; }}
接下来就是最关键的 internalmodal.tsx :
export default class internalmodal { private props; render(props) { const {...} = this.props; this.createcontainer(); const icon = require('../../assets/icon/info.svg') as string; const modaldom = ...; reactdom.render({modaldom}, modalcontainer, () => { if (visible) { this.show(); } }); } ... createcontainer() { if (!modalcontainer) { modalcontainer = document.createelement('p'); document.body.appendchild(modalcontainer); } } destroy() { if (modalcontainer) { reactdom.unmountcomponentatnode(modalcontainer); } } show() { if (modalcontainer) { modalcontainer.style.display = 'block'; } } hide() { if (modalcontainer) { modalcontainer.style.display = 'none'; } }}
从代码可以发现 internalmodal 的实现要点:
作为一个普通 js 类 (并没有继承 react.component) ,提供一个 render 方法,render 中通过reactdom.render(element, container[, callback])渲染弹出窗口
在 document 上创建一个 p container 乘放 modal,通过 css display 控制显示/隐藏,其实也可以使用 react portal.
可以用一些第三方库比如react-transition-group 来增强 modal 显示/隐藏的动画效果。
推荐学习:《react视频教程》
以上就是react中modal的用法是什么的详细内容。
