書籍完整目錄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