精益 React 学习指南 Lean React- 4.1 react 代码规范

书籍完整目录

4.1 react 代码规范

  • 关于

  • 基础规范

  • 组件结构

  • 命名规范

  • jsx 书写规范

  • eslint-plugin-react

关于

代码的设计上,每个团队可能都有一定的代码规范和模式,好的代码规范能够提高代码的可读性便于协作沟通,好的模式能够上层设计上避免不必要的 bug 出现。本节会参考社区提供一些 React 的规范和优秀的设计模式。

基础规范

  1. 统一全部采用 Es6

  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;

命名规范

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

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...