来自于Airbnb React/JSX 中文编码规范javascript
算是最合理的React/JSX编码规范之一了html
每一个文件只写一个模块.java
react/no-multi-comp
.React.createElement
,除非从一个非JSX的文件中初始化你的app.Class vs React.createClass vs statelessnode
refs
, 推荐使用 class extends React.Component
而不是 React.createClass
,除非你有充足的理由来使用这些方法. react/prefer-es6-class
react/prefer-stateless-function
// bad const Listing = React.createClass({ // ... render() { return <div>{this.state.hello}</div>; } }); // good class Listing extends React.Component { // ... render() { return <div>{this.state.hello}</div>; } }
若是你的模块没有状态或是没有引用`refs`, 推荐使用普通函数(非箭头函数)而不是类:
// bad class Listing extends React.Component { render() { return <div>{this.props.hello}</div>; } } // bad (relying on function name inference is discouraged) const Listing = ({ hello }) => ( <div>{hello}</div> ); // good function Listing({ hello }) { return <div>{hello}</div>; }
.jsx
扩展名.ReservationCard.jsx
. - 引用命名: React模块名使用帕斯卡命名,实例使用骆驼式命名. eslint: react/jsx-pascal-case
react
// bad import reservationCard from './ReservationCard'; // good import ReservationCard from './ReservationCard'; // bad const ReservationItem = <ReservationCard />; // good const reservationItem = <ReservationCard />;
模块命名: 模块使用当前文件名同样的名称. 好比 ReservationCard.jsx
应该包含名为 ReservationCard
的模块. 可是,若是整个文件夹是一个模块,使用 index.js
做为入口文件,而后直接使用 index.js
或者文件夹名做为模块的名称:git
// bad import Footer from './Footer/Footer'; // bad import Footer from './Footer/index'; // good import Footer from './Footer';
displayName
应该为高阶模块名和传入模块名的组合. 例如, 高阶模块 withFoo()
, 当传入一个 Bar
模块的时候, 生成的模块名 displayName
应该为 withFoo(Bar)
.为何?一个模块的
displayName
可能会在开发者工具或者错误信息中使用到,所以有一个能清楚的表达这层关系的值能帮助咱们更好的理解模块发生了什么,更好的Debug.es6
// bad export default function withFoo(WrappedComponent) { return function WithFoo(props) { return <WrappedComponent {...props} foo />; } } // good export default function withFoo(WrappedComponent) { function WithFoo(props) { return <WrappedComponent {...props} foo />; } const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; WithFoo.displayName = `withFoo(${wrappedComponentName})`; return WithFoo; }
为何?对于
style
和className
这样的属性名,咱们都会默认它们表明一些特殊的含义,如元素的样式,CSS class的名称。在你的应用中使用这些属性来表示其余的含义会使你的代码更难阅读,更难维护,而且可能会引发bug。github
// bad <MyComponent style="fancy" /> // good <MyComponent variant="fancy" />
不要使用 displayName
来命名React模块,而是使用引用来命名模块, 如 class 名称.设计模式
// bad export default React.createClass({ displayName: 'ReservationCard', // stuff goes here }); // good export default class ReservationCard extends React.Component { }
遵循如下的JSX语法缩进/格式. eslint: react/jsx-closing-bracket-location
数组
// bad <Foo superLongParam="bar" anotherSuperLongParam="baz" /> // good, 有多行属性的话, 新建一行关闭标签 <Foo superLongParam="bar" anotherSuperLongParam="baz" /> // 若能在一行中显示, 直接写成一行 <Foo bar="bar" /> // 子元素按照常规方式缩进 <Foo superLongParam="bar" anotherSuperLongParam="baz" > <Quux /> </Foo>
"
), 其余均使用单引号('
). eslint: jsx-quotes
为何? HTML属性也是用双引号, 所以JSX的属性也遵循此约定.
// bad <Foo bar='bar' /> // good <Foo bar="bar" /> // bad <Foo style={{ left: "20px" }} /> // good <Foo style={{ left: '20px' }} />
老是在自动关闭的标签前加一个空格,正常状况下也不须要换行. eslint: no-multi-spaces
, react/jsx-space-before-closing
// bad <Foo/> // very bad <Foo /> // bad <Foo /> // good <Foo />
不要在JSX {}
引用括号里两边加空格. eslint: react/jsx-curly-spacing
// bad <Foo bar={ baz } /> // good <Foo bar={baz} />
JSX属性名使用骆驼式风格camelCase
.
// bad <Foo UserName="hello" phone_number={12345678} /> // good <Foo userName="hello" phoneNumber={12345678} />
若是属性值为 true
, 能够直接省略. eslint: react/jsx-boolean-value
// bad <Foo hidden={true} /> // good <Foo hidden />
<img>
标签老是添加 alt
属性. 若是图片以presentation(感受是以相似PPT方式显示?)方式显示,alt
可为空, 或者<img>
要包含role="presentation"
. eslint: jsx-a11y/img-has-alt
// bad <img src="hello.jpg" /> // good <img src="hello.jpg" alt="Me waving hello" /> // good <img src="hello.jpg" alt="" /> // good <img src="hello.jpg" role="presentation" />
alt
值里使用如 "image", "photo", or "picture"包括图片含义这样的词, 中文也同样. eslint: jsx-a11y/img-redundant-alt
为何? 屏幕助读器已经把
img
标签标注为图片了, 因此没有必要再在alt
里说明了.
// bad <img src="hello.jpg" alt="Picture of me waving hello" /> // good <img src="hello.jpg" alt="Me waving hello" />
使用有效正确的 aria role
属性值 ARIA roles. eslint: jsx-a11y/aria-role
// bad - not an ARIA role <div role="datepicker" /> // bad - abstract ARIA role <div role="range" /> // good <div role="button" />
accessKey
属性. eslint: jsx-a11y/no-access-key
为何? 屏幕助读器在键盘快捷键与键盘命令时形成的不统一性会致使阅读性更加复杂.
// bad <div accessKey="h" /> // good <div />
避免使用数组的index来做为属性key
的值,推荐使用惟一ID. (为何?)
// bad {todos.map((todo, index) => <Todo {...todo} key={index} /> )} // good {todos.map(todo => ( <Todo {...todo} key={todo.id} /> ))}
defaultProps
属性.为何? propTypes 能够做为模块的文档说明, 而且声明 defaultProps 的话意味着阅读代码的人不须要去假设一些默认值。更重要的是, 显示的声明默认属性可让你的模块跳过属性类型的检查.
// bad function SFC({ foo, bar, children }) { return <div>{foo}{bar}{children}</div>; } SFC.propTypes = { foo: PropTypes.number.isRequired, bar: PropTypes.string, children: PropTypes.node, }; // good function SFC({ foo, bar }) { return <div>{foo}{bar}</div>; } SFC.propTypes = { foo: PropTypes.number.isRequired, bar: PropTypes.string, }; SFC.defaultProps = { bar: '', children: null, };
老是在Refs里使用回调函数. eslint: react/no-string-refs
// bad <Foo ref="myRef" /> // good <Foo ref={(ref) => { this.myRef = ref; }} />
将多行的JSX标签写在 ()
里. eslint: react/wrap-multilines
// bad render() { return <MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent>; } // good render() { return ( <MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent> ); } // good, 单行能够不须要 render() { const body = <div>hello</div>; return <MyComponent>{body}</MyComponent>; }
对于没有子元素的标签来讲老是本身关闭标签. eslint: react/self-closing-comp
// bad <Foo className="stuff"></Foo> // good <Foo className="stuff" />
若是模块有多行的属性, 关闭标签时新建一行. eslint: react/jsx-closing-bracket-location
// bad <Foo bar="bar" baz="baz" /> // good <Foo bar="bar" baz="baz" />
使用箭头函数来获取本地变量.
function ItemList(props) { return ( <ul> {props.items.map((item, index) => ( <Item key={item.key} onClick={() => doSomethingWith(item.name, index)} /> ))} </ul> ); }
render()
里使用事件处理方法时,提早在构造函数里把 this
绑定上去. eslint: react/jsx-no-bind
为何? 在每次
render
过程当中, 再调用bind
都会新建一个新的函数,浪费资源.
// bad class extends React.Component { onClickDiv() { // do stuff } render() { return <div onClick={this.onClickDiv.bind(this)} /> } } // good class extends React.Component { constructor(props) { super(props); this.onClickDiv = this.onClickDiv.bind(this); } onClickDiv() { // do stuff } render() { return <div onClick={this.onClickDiv} /> } }
_
前缀,本质上它并非私有的.为何?
_
下划线前缀在某些语言中一般被用来表示私有变量或者函数。可是不像其余的一些语言,在JS中没有原生支持所谓的私有变量,全部的变量函数都是共有的。尽管你的意图是使它私有化,在以前加上下划线并不会使这些变量私有化,而且全部的属性(包括有下划线前缀及没有前缀的)都应该被视为是共有的。了解更多详情请查看Issue #1024, 和 #490 。
// bad React.createClass({ _onClickSubmit() { // do stuff }, // other stuff }); // good class extends React.Component { onClickSubmit() { // do stuff } // other stuff }
在 render
方法中老是确保 return
返回值. eslint: react/require-render-return
// bad render() { (<div />); } // good render() { return (<div />); }
class extends React.Component
的生命周期函数:static
方法constructor
构造函数getChildContext
获取子元素内容componentWillMount
模块渲染前componentDidMount
模块渲染后componentWillReceiveProps
模块将接受新的数据shouldComponentUpdate
判断模块需不须要从新渲染componentWillUpdate
上面的方法返回 true
, 模块将从新渲染componentDidUpdate
模块渲染结束componentWillUnmount
模块将从DOM中清除, 作一些清理任务onClickSubmit()
或 onChangeDescription()
render
里的 getter 方法 如 getSelectReason()
或 getFooterContent()
renderNavigation()
或 renderProfilePicture()
render
render() 方法如何定义 propTypes
, defaultProps
, contextTypes
, 等等其余属性...
import React, { PropTypes } from 'react'; const propTypes = { id: PropTypes.number.isRequired, url: PropTypes.string.isRequired, text: PropTypes.string, }; const defaultProps = { text: 'Hello World', }; class Link extends React.Component { static methodsAreOk() { return true; } render() { return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a> } } Link.propTypes = propTypes; Link.defaultProps = defaultProps; export default Link;
React.createClass
的生命周期函数,与使用class稍有不一样: eslint: react/sort-comp
displayName
设定模块名称propTypes
设置属性的类型contextTypes
设置上下文类型childContextTypes
设置子元素上下文类型mixins
添加一些mixinsstatics
defaultProps
设置默认的属性值getDefaultProps
获取默认属性值getInitialState
或者初始状态getChildContext
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
onClickSubmit()
or onChangeDescription()
render
like getSelectReason()
or getFooterContent()
renderNavigation()
or renderProfilePicture()
render
isMounted
. eslint: react/no-is-mounted
为何?
isMounted
反人类设计模式:(), 在 ES6 classes 中没法使用, 官方将在将来的版本里删除此方法.