書籍完整目錄
4.1 react 代碼規範
-
關於
-
基礎規範
-
組件結構
-
命名規範
-
jsx 書寫規範
-
eslint-plugin-react
關於
在代碼的設計上,每個團隊可能都有一定的代碼規範和模式,好的代碼規範能夠提高代碼的可讀性便於協作溝通,好的模式能夠上層設計上避免不必要的 bug 出現。本節會參考社區提供一些 React 的規範和優秀的設計模式。
基礎規範
-
統一全部採用 Es6
-
組件文件名稱採用大駝峯命名
組件結構
總體規則: 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
-
組件方法名稱:避免使用下劃線開頭的命名
jsx 書寫規範
-
自閉合
// 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
規範可以使用 eslint-plugin-react 插件來強制實施,規則和配置可查看
https://github.com/yannickcr/eslint-plugin-react
更多 react 代碼規範可參考 https://github.com/airbnb/javascript/tree/master/react