#React 编程规范(by Airbnb)
##基本规则
- 每个文件只包含一个 React 组件
- 使用
JSX
语法 - 除非是从一个非
JSX
文件中初始化 app,否则不要使用React.createElement
Class vs React.createClass
- 除非有更好的理由使用混淆(mixins),否则就使用组件类继承
React.Component
。eslint 规则:react/prefer-es6-class
1 | // bad |
##命名
- 扩展名: 使用
jsx
作为 React 组件的扩展名 - 文件名: 文件命名采用帕斯卡命名法,如:
ReservationCard.jsx
- 引用名: 组件引用采用帕斯卡命名法,其实例采用驼峰式命名法。eslint rules: react/jsx-pascal-case
1 | // bad |
- 组件命名: 使用文件名作为组件名。例如:
ReservationCard.jsx
组件的引用名应该是ReservationCard
。然而,对于一个目录的根组件,应该使用index.jsx
作为文件名,使用目录名作为组件名。
1 | // bad |
##声明
- 不要通过
displayName
来命名组件,通过引用来命名组件
1 | // bad |
##对齐
- 对于
JSX
语法,遵循下面的对齐风格。eslint rules: react/jsx-closing-bracket-location
1 | // bad |
##引号
- 对于
JSX
使用双引号,对其它所有 JS 属性使用单引号
为什么?因为 JSX 属性不能包含被转移的引号,并且双引号使得如
"don't"
一样的连接词很容易被输入。常规的 HTML 属性也应该使用双引号而不是单引号,JSX 属性反映了这个约定。
eslint rules: jsx-quotes
1 | // bad |
##空格
- 在自闭和标签之前留一个空格
1 | // bad |
##属性
- 属性名采用驼峰式命名法
1 | // bad |
##括号
- 当组件跨行时,要用括号包裹 JSX 标签。eslint rules: react/wrap-multilines
1 | /// bad |
##标签
- 没有子组件的父组件使用自闭和标签。eslint rules: react/self-closing-comp
1 | // bad |
- 如果组件有多行属性,闭合标签应写在新的一行上。eslint rules: react/jsx-closing-bracket-location
1 | // bad |
##方法
- 不要对 React 组件的内置方法使用
underscore
前缀
1 | // bad |
##顺序
- 继承 React.Component 的类的方法遵循下面的顺序
- constructor
- optional static methods
- getChildContext
- componentWillMount
- componentDidMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
- clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
- getter methods for render like getSelectReason() or getFooterContent()
- Optional render methods like renderNavigation() or renderProfilePicture()
- render
- 怎么定义 propTypes,defaultProps,contextTypes 等等…
1 | import React, { PropTypes } from 'react'; |
- 使用 React.createClass 时,方法顺序如下:
- displayName
- propTypes
- contextTypes
- childContextTypes
- mixins
- statics
- defaultProps
- getDefaultProps
- getInitialState
- getChildContext
- componentWillMount
- componentDidMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
- clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
- getter methods for render like getSelectReason() or getFooterContent()
- Optional render methods like renderNavigation() or renderProfilePicture()
- render
eslint rules: react/sort-comp