4.1 react 代碼規範

關於

  • 基礎規範javascript

  • 組件結構java

  • 命名規範react

  • jsx 書寫規範git

  • eslint-plugin-reactgithub

關於

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

基礎規範

  1. 統一所有采用 Es6數組

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

組件結構

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

  • Es6 class 定義規範:this

  1. static 方法

  2. constructor

  3. getChildContext

  4. componentWillMount

  5. componentDidMount

  6. componentWillReceiveProps

  7. shouldComponentUpdate

  8. componentWillUpdate

  9. componentDidUpdate

  10. componentWillUnmount

  11. clickHandlers + eventHandlers 如 onClickSubmit() 或 onChangeDescription()

  12. getter methods for render 如 getSelectReason() 或 getFooterContent()

  13. render methods 如 renderNavigation() 或 renderProfilePicture()

  14. render

以 Es6 Class 定義的組件爲例;

const defaultProps = {
  name: 'Guest'
};
const propTypes = {
  name: React.PropTypes.string
};
class Person extends React.Component {

  // 構造函數
  constructor (props) {
    super(props);
    // 定義 statethis.state = { smiling: false };
    // 定義 eventHandlerthis.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



相關文章
相關標籤/搜索