这篇看ant Desgin of react的button按钮的js代码,js代码部分是typescript+react写的。

button组件里面引用了哪些组件:

  1. import * as React from 'react';
  2. import { findDOMNode } from 'react-dom';
  3. import PropTypes from 'prop-types';
  4. import classNames from 'classnames';
  5. import Icon from '../icon';
  6. import Group from './button-group';
  • Reactreact-dom是react要引用的,这里不多解释。
  • prop-types是用来检验传给组件props的类型,在props上运行类型检查,在下面代码中用到
  • className是用来添加多个className

先看下整体代码:

  1. import * as React from 'react';
  2. import { findDOMNode } from 'react-dom';
  3. import PropTypes from 'prop-types';
  4. import classNames from 'classnames';
  5. import Icon from '../icon';
  6. import Group from './button-group';
  7. const rxTwoCNChar = /^[\u4e00-\u9fa5]{2}$/;
  8. const isTwoCNChar = rxTwoCNChar.test.bind(rxTwoCNChar);
  9. /**
  10. * 判断是否是字符串类型
  11. */
  12. function isString(str: any) {
  13. return typeof str === 'string';
  14. }
  15. /**
  16. * 多个中文间插入空格
  17. * @param {Object} child 组件的子内容
  18. * @param {Boolean} needInserted 是否插入空格
  19. * @returns {ReactElement}
  20. */
  21. // Insert one space between two chinese characters automatically.
  22. function insertSpace(child: React.ReactChild, needInserted: boolean) {
  23. // Check the child if is undefined or null.
  24. if (child == null) {
  25. return;
  26. }
  27. const SPACE = needInserted ? ' ' : '';
  28. // strictNullChecks oops.
  29. if (typeof child !== 'string' && typeof child !== 'number' &&
  30. isString(child.type) && isTwoCNChar(child.props.children)) {
  31. return React.cloneElement(child, {},
  32. child.props.children.split('').join(SPACE));
  33. }
  34. if (typeof child === 'string') {
  35. if (isTwoCNChar(child)) {
  36. child = child.split('').join(SPACE);
  37. }
  38. return <span>{child}</span>;
  39. }
  40. return child;
  41. }
  42. /**
  43. * 类型别名,这个类型的只能是对应的值
  44. */
  45. export type ButtonType = 'default' | 'primary' | 'ghost' | 'dashed' | 'danger';
  46. export type ButtonShape = 'circle' | 'circle-outline';
  47. export type ButtonSize = 'small' | 'default' | 'large';
  48. export type ButtonHTMLType = 'submit' | 'button' | 'reset';
  49. /**
  50. * 声明一个接口BaseButtonProps
  51. */
  52. export interface BaseButtonProps {
  53. type?: ButtonType;
  54. icon?: string;
  55. shape?: ButtonShape;
  56. size?: ButtonSize;
  57. loading?: boolean | { delay?: number };
  58. prefixCls?: string;
  59. className?: string;
  60. ghost?: boolean;
  61. }
  62. /**
  63. * a标签的参数组合
  64. */
  65. export type AnchorButtonProps = {
  66. href: string;
  67. target?: string;
  68. onClick?: React.MouseEventHandler<HTMLAnchorElement>;
  69. } & BaseButtonProps & React.AnchorHTMLAttributes<HTMLAnchorElement>;
  70. /**
  71. * button标签的参数组合
  72. */
  73. export type NativeButtonProps = {
  74. htmlType?: ButtonHTMLType;
  75. onClick?: React.MouseEventHandler<HTMLButtonElement>;
  76. } & BaseButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>;
  77. /**
  78. * 类型别名
  79. */
  80. export type ButtonProps = AnchorButtonProps | NativeButtonProps;
  81. /**
  82. * button class声明
  83. */
  84. export default class Button extends React.Component<ButtonProps, any> {
  85. static Group: typeof Group;
  86. static __ANT_BUTTON = true;
  87. /**
  88. * 设置props默认值
  89. */
  90. static defaultProps = {
  91. prefixCls: 'ant-btn',
  92. loading: false,
  93. ghost: false,
  94. };
  95. /**
  96. * props类型校验
  97. */
  98. static propTypes = {
  99. type: PropTypes.string,
  100. shape: PropTypes.oneOf(['circle', 'circle-outline']),
  101. size: PropTypes.oneOf(['large', 'default', 'small']),
  102. htmlType: PropTypes.oneOf(['submit', 'button', 'reset']),
  103. onClick: PropTypes.func,
  104. loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
  105. className: PropTypes.string,
  106. icon: PropTypes.string,
  107. };
  108. timeout: number;
  109. delayTimeout: number;
  110. /**
  111. * 构造函数
  112. */
  113. constructor(props: ButtonProps) {
  114. super(props);
  115. this.state = {
  116. loading: props.loading,
  117. clicked: false,
  118. hasTwoCNChar: false,
  119. };
  120. }
  121. /**
  122. * 组件渲染之后调用,只调用一次。
  123. */
  124. componentDidMount() {
  125. this.fixTwoCNChar();
  126. }
  127. /**
  128. * props改变时调用触发,nextProps.loading赋值到setState的loading
  129. * @param nextProps
  130. */
  131. componentWillReceiveProps(nextProps: ButtonProps) {
  132. const currentLoading = this.props.loading;
  133. const loading = nextProps.loading;
  134. if (currentLoading) {
  135. clearTimeout(this.delayTimeout);
  136. }
  137. if (typeof loading !== 'boolean' && loading && loading.delay) {
  138. this.delayTimeout = window.setTimeout(() => this.setState({ loading }), loading.delay);
  139. } else {
  140. this.setState({ loading });
  141. }
  142. }
  143. /**
  144. * 组件更新完成后调用
  145. */
  146. componentDidUpdate() {
  147. this.fixTwoCNChar();
  148. }
  149. /**
  150. * 组件将要卸载时调用,清除定时器
  151. */
  152. componentWillUnmount() {
  153. if (this.timeout) {
  154. clearTimeout(this.timeout);
  155. }
  156. if (this.delayTimeout) {
  157. clearTimeout(this.delayTimeout);
  158. }
  159. }
  160. /**
  161. * 判断botton的内容是否有两个中文字
  162. */
  163. fixTwoCNChar() {
  164. // Fix for HOC usage like <FormatMessage />
  165. const node = (findDOMNode(this) as HTMLElement);
  166. const buttonText = node.textContent || node.innerText;
  167. if (this.isNeedInserted() && isTwoCNChar(buttonText)) {
  168. if (!this.state.hasTwoCNChar) {
  169. this.setState({
  170. hasTwoCNChar: true,
  171. });
  172. }
  173. } else if (this.state.hasTwoCNChar) {
  174. this.setState({
  175. hasTwoCNChar: false,
  176. });
  177. }
  178. }
  179. /**
  180. * 单击事件
  181. */
  182. handleClick: React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement> = e => {
  183. // Add click effect
  184. this.setState({ clicked: true });
  185. clearTimeout(this.timeout);
  186. this.timeout = window.setTimeout(() => this.setState({ clicked: false }), 500);
  187. const onClick = this.props.onClick;
  188. if (onClick) {
  189. (onClick as React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>)(e);
  190. }
  191. }
  192. /**
  193. * 判断子节点只有一个和是否图标
  194. */
  195. isNeedInserted() {
  196. const { icon, children } = this.props;
  197. return React.Children.count(children) === 1 && !icon;
  198. }
  199. /**
  200. * 组件内容
  201. */
  202. render() {
  203. const {
  204. type, shape, size, className, children, icon, prefixCls, ghost, loading: _loadingProp, ...rest
  205. } = this.props;
  206. const { loading, clicked, hasTwoCNChar } = this.state;
  207. // large => lg
  208. // small => sm
  209. let sizeCls = '';
  210. switch (size) {
  211. case 'large':
  212. sizeCls = 'lg';
  213. break;
  214. case 'small':
  215. sizeCls = 'sm';
  216. default:
  217. break;
  218. }
  219. /**
  220. * 拼接className
  221. */
  222. const classes = classNames(prefixCls, className, {
  223. [`${prefixCls}-${type}`]: type,
  224. [`${prefixCls}-${shape}`]: shape,
  225. [`${prefixCls}-${sizeCls}`]: sizeCls,
  226. [`${prefixCls}-icon-only`]: !children && icon,
  227. [`${prefixCls}-loading`]: loading,
  228. [`${prefixCls}-clicked`]: clicked,
  229. [`${prefixCls}-background-ghost`]: ghost,
  230. [`${prefixCls}-two-chinese-chars`]: hasTwoCNChar,
  231. });
  232. /**
  233. * 设置图标
  234. */
  235. const iconType = loading ? 'loading' : icon;
  236. const iconNode = iconType ? <Icon type={iconType} /> : null;
  237. const kids = (children || children === 0)
  238. ? React.Children.map(children, child => insertSpace(child, this.isNeedInserted())) : null;
  239. /**
  240. * 判断是a标签还是button标签
  241. */
  242. if ('href' in rest) {
  243. return (
  244. <a
  245. {...rest}
  246. className={classes}
  247. onClick={this.handleClick}
  248. >
  249. {iconNode}{kids}
  250. </a>
  251. );
  252. } else {
  253. // React does not recognize the `htmlType` prop on a DOM element. Here we pick it out of `rest`.
  254. const { htmlType, ...otherProps } = rest;
  255. return (
  256. <button
  257. {...otherProps}
  258. type={htmlType || 'button'}
  259. className={classes}
  260. onClick={this.handleClick}
  261. >
  262. {iconNode}{kids}
  263. </button>
  264. );
  265. }
  266. }
  267. }

因为按钮的逻辑没那么复杂,里面很多都是对外开放的弄能和样式的一些对应,所以就在代码上加了注释,能很快理解里面的代码

button JS篇ant Design of react的更多相关文章

  1. button JS篇ant Design of react之二

    最近更新有点慢,更新慢的原因最近在看 <css世界>这本书,感觉很不错 <JavaScript高级程序设计> 这本书已经看了很多遍了,主要是复习前端的基础知识,基础知识经常会过 ...

  2. ElementUI(vue UI库)、iView(vue UI库)、ant design(react UI库)中组件的区别

    ElementUI(vue UI库).iView(vue UI库).ant design(react UI库)中组件的区别: 事项 ElementUI iView ant design 全局加载进度条 ...

  3. 同时使用 Ant Design of React 中 Mention 和 Form

    使用场景,在一个列表中,点击每一行会弹出一个表单,通过修改表单数据并提交来修改这一行的数据,其中某个数据的填写需要通过Mention实现动态提示及自动补全的功能. 具体效果为: 遇到的问题: 1.希望 ...

  4. Ant Design of React 框架使用总结1

    一.  为什么要用UI 框架 统一了样式交互动画 . Ui框架会对样式,交互动画进行统一,保证了系统风格完整统一,不像拼凑起来的. 兼容性 ,不是去兼容IE 6 7 8那些低版本浏览器,而是对主流的标 ...

  5. 十九、React UI框架Antd(Ant Design)的使用——及react Antd的使用 button组件 Icon组件 Layout组件 DatePicker日期组件

    一.Antd(Ant Design)的使用:引入全部Css样式 1.1 antd官网: https://ant.design/docs/react/introduce-cn 1.2 React中使用A ...

  6. React + Ant Design网页,配置

    第一个React + Ant Design网页(一.配置+编写主页) 引用博主的另外一篇VUE2.0+ElementUI教程, 请移步:  https://blog.csdn.net/u0129070 ...

  7. Vue.js高效前端开发 • 【Ant Design of Vue框架基础】

    全部章节 >>>> 文章目录 一.Ant Design of Vue框架 1.Ant Design介绍 2.Ant Design of Vue安装 3.Ant Design o ...

  8. Ant Design React按需加载

    Ant Design是阿里巴巴为React做出的组件库,有统一的样式及一致的用户体验 官网地址:https://ant.design 1.安装: npm install ant --save 2.引用 ...

  9. react的ant design的UI组件库

    PC官网:https://ant.design/ 移动端网址:https://mobile.ant.design/docs/react/introduce-cn antd-mobile :是 Ant ...

随机推荐

  1. jquery操作iframe的方法:父页面和子页面相互操作的方法

    今天在弄jquery操作iframe中元素:先由iframe中的子页面b.html给外面的父页面a.html页面传值,再将a.html页面计算机的值放到b.html页面上,这里就用到子页面和父页面相互 ...

  2. ThreadLocal的原理,源码深度分析及使用

    文章简介 ThreadLocal应该都比较熟悉,这篇文章会基于ThreadLocal的应用以及实现原理做一个全面的分析 内容导航 什么是ThreadLocal ThreadLocal的使用 分析Thr ...

  3. octotree-chrome插件,Github代码阅读神器

    1.下载octotree-chrome插件 下载地址 2.安装问题 由于新版chrome为了安全,已经不支持像以前一样拖拽插件进行安装,只能从其 Chrome Web Store 下载安装扩展程序. ...

  4. DuelJS 介绍

    DuelJS 是什么? DuelJS是一个快速和小型的JavaScript库,可以帮助实现浏览器tab页主从关系的切换.使用它可以优化你浏览器和服务器之间的通信,以及你浏览器内部tab页之间的通信. ...

  5. win10下 anaconda 环境下python2和python3版本转换

    在cmd的环境下,输入以下命令安装Python2.7的环境 conda create -n python27 python=2.7 anaconda 上面的代码创建了一个名为python27的pyth ...

  6. Python消息队列(RabbitMQ)

    RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用.可维护多个队列,可实现消息的一对一和广播等方式发送 RabbitMQ是一个开源的AMQP实现 ...

  7. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之十 || AOP面向切面编程浅解析:简单日志记录 + 服务切面缓存

    代码已上传Github+Gitee,文末有地址 上回<从壹开始前后端分离[ .NET Core2.0 Api + Vue 2.0 + AOP + 分布式]框架之九 || 依赖注入IoC学习 + ...

  8. 【神经网络篇】--RNN递归神经网络初始与详解

    一.前述 传统的神经网络每个输入节点之间没有联系, RNN (对中间信息保留): 由图可知,比如第二个节点的输入不仅依赖于本身的输入U1,而且依赖上一个节点的输入W0,U0,同样第三个节点依赖于前两个 ...

  9. python接口自动化(四)--接口测试工具介绍(详解)

    简介 “工欲善其事必先利其器”,通过前边几篇文章的介绍,大家大致对接口有了进一步的认识.那么接下来让我们看看接口测试的工具有哪些. 目前,市场上有很多支持接口测试的工具.利用工具进行接口测试,能够提供 ...

  10. 微服务实战(三):落地微服务架构到直销系统(构建基于RabbitMq的消息总线)

    从前面文章可以看出,消息总线是EDA(事件驱动架构)与微服务架构的核心部件,没有消息总线,就无法很好的实现微服务之间的解耦与通讯.通常我们可以利用现有成熟的消息代理产品或云平台提供的消息服务来构建自己 ...