精益 React 學習指南 (Lean React)- 4.1 react 代碼規範

書籍完整目錄javascript

4.1 react 代碼規範

圖片描述

  • 關於java

  • 基礎規範react

  • 組件結構git

  • 命名規範github

  • jsx 書寫規範segmentfault

  • eslint-plugin-react設計模式

關於

在代碼的設計上,每一個團隊可能都有必定的代碼規範和模式,好的代碼規範可以提升代碼的可讀性便於協做溝通,好的模式可以上層設計上避免沒必要要的 bug 出現。本節會參考社區提供一些 React 的規範和優秀的設計模式。數組

基礎規範

  1. 統一所有采用 Es6less

  2. 組件文件名稱採用大駝峯命名函數

組件結構

整體規則: stateless(Function) 優先於 Es6 Class 優先於 React.createClass;
書寫規則: 規範組件內部方法的定義順序

  • Es6 class 定義規範:

  1. static 方法

  2. constructor

  3. getChildContext

  4. componentWillMount

  5. componentDidMount

  6. componentWillReceiveProps

  7. shouldComponentUpdate

  8. componentWillUpdate

  9. componentDidUpdate

  10. componentWillUnmount

  11. clickHandlers + eventHandlersonClickSubmit()onChangeDescription()

  12. getter methods for rendergetSelectReason()getFooterContent()

  13. render methodsrenderNavigation()renderProfilePicture()

  14. 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

相關文章
相關標籤/搜索