how-antd-create-notification

github: 地址 gitbook: 地址

Antd 是怎么使用 React 制作 notification 组件的

作者:markzzw 时间:2019-12-18 本文相关代码地址:github

简介

通过了解 antd 的制作方法以及观看源码,完成组件的简单实现;

目录

中心思想

简单的来说就是使用 notification component 渲染出 notice components,然后使用 notification class 中的方法生成对应的位置的 notification component

配图

中心思想

为什么是这样的

先来看看 antd 是怎么使用 notification 组件的:notification.open(config),可以看出,生成这个组件是使用的一个方法,而不是像写 react 那样直接写成 <Component {...props} />,所以最终使用的 notification 是一个实例化了的类,里面有一些方法能够生成 notification componentnotice component

notification component

不难理解,我们使用 state 进行每个组件中的 notice 进行管理,然后将其渲染,相当于是每个实例中单独管理自己的 notice list,这里需要将其看做成为一个实例化的类,并且因为使用了 react 会因为 state 的改变而重绘,所以 state 是最佳载体

notice component

每一个 notice 便是我们消息的承载体,可以手动关闭,也可以设置关闭时间,在时间结束时关闭,并且为了更好的用户体验,在鼠标移动上去时清除掉定时器,移开时重新设置定时器,这样的用户体验还可以设置在轮播图这一类具有定时器的组件中,在鼠标移动上去的时候,不进行图片更换,移开之后再进行(可以适当变形,轮播图可以立即执行一次切换图片的动作);

notification class

我们使用 NotificationFactory 中的 notice 进行组件的渲染,那么我们来看看这个类做了些什么事情

  1. 使用 this.notifications[placement] 存储每个位置上的内容,当做缓存

  2. 调用 open 进行 propsoptions 的组装

  3. 调用 getNotificationInstance 进行组件渲染,主要使用 ReactDOM.render(<Notification {...props} ref={ref} />, div) 将组件渲染到指定的 DOM 节点,这也是 notification class 的最主要的代码,为什么要使用 ref,因为还需要调用 notification componentaddNotice 方法,但是因为使用了 <Notification /> 的方式实例化了组件,所以如果需要获取到组件的实例,就需要用到 ref

message component

messages componentnotification component 其实是一个载体,只是展示的东西不同,所以只需要重新定义一些参数即可

参考资料

Last updated