书籍完整目录javascript
关于java
基础规范react
组件结构git
命名规范github
jsx 书写规范segmentfault
eslint-plugin-react设计模式
在代码的设计上,每一个团队可能都有必定的代码规范和模式,好的代码规范可以提升代码的可读性便于协做沟通,好的模式可以上层设计上避免没必要要的 bug 出现。本节会参考社区提供一些 React 的规范和优秀的设计模式。数组
统一所有采用 Es6less
组件文件名称采用大驼峰命名函数
整体规则: stateless(Function) 优先于 Es6 Class 优先于 React.createClass;
书写规则: 规范组件内部方法的定义顺序
Es6 class 定义规范:
static
方法
constructor
getChildContext
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
clickHandlers + eventHandlers 如 onClickSubmit()
或 onChangeDescription()
getter methods for render
如 getSelectReason()
或 getFooterContent()
render methods 如 renderNavigation()
或 renderProfilePicture()
render
以 Es6 Class 定义的组件为例;
const defaultProps = { name: 'Guest' }; const propTypes = { name: React.PropTypes.string }; class Person extends React.Component { // 构造函数 constructor (props) { super(props); // 定义 state this.state = { smiling: false }; // 定义 eventHandler this.handleClick = this.handleClick.bind(this); } // 生命周期方法 componentWillMount () {}, componentDidMount () {}, componentWillUnmount () {}, // getters and setters get attr() {} // handlers handleClick() {}, // render renderChild() {}, render () {}, } /** * 类变量定义 */ Person.defaultProps = defaultProps; /** * 统一都要定义 propTypes * @type {Object} */ Person.propTypes = propTypes;
组件名称:大驼峰
属性名称:小驼峰
事件处理函数:handleSomething
自定义事件属性名称:onSomething={this.handleSomething}
key: 不能使用数组 index ,构造或使用惟一的 id
组件方法名称:避免使用下划线开头的命名
自闭合
// bad <Foo className="stuff"></Foo> // good <Foo className="stuff" />
属性对齐
// bad <Foo superLongParam="bar" anotherSuperLongParam="baz" /> // good <Foo superLongParam="bar" anotherSuperLongParam="baz" /> // if props fit in one line then keep it on the same line <Foo bar="bar" />
返回
// bad render() { return <MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent>; } // good render() { return ( <MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent> ); } // good, when single line render() { const body = <div>hello</div>; return <MyComponent>{body}</MyComponent>; }
规范能够使用 eslint-plugin-react 插件来强制实施,规则和配置可查看
https://github.com/yannickcr/eslint-plugin-react
更多 react 代码规范可参考 https://github.com/airbnb/javascript/tree/master/react