React规范

    • 在使用模块导入时,倾向于不添加后缀,如果存在同名但不同后缀的文件,构建工具将无法决定哪一个是需要引入的模块。

    • [强制]组件文件使用一致的.js.jsx后缀。

      所有组件文件的后缀名从.js.jsx中任选其一。

      不应在项目中出现部分组件为.js文件,部分为.jsx的情况。

    • [强制]每一个文件以export default的形式暴露一个组件。

      允许一个文件中存在多个不同的组件,但仅允许通过export default暴露一个组件,其它组件均定义为内部组件。

    • [强制]每个存放组件的目录使用一个index.js以命名导出的形式暴露所有组件。

      同目录内的组件相互引用使用import Foo from './Foo';进行。

      引用其它目录的组件使用import {Foo} from '../component';进行。

      建议使用等插件自动生成index.js的内容。

    • [强制]组件名为PascalCase。

      包括函数组件,名称均为PascalCase。

    • [强制]组件名称与文件名称保持相同。

      同时组件名称应当能体现出组件的功能,以便通过观察文件名即确定使用哪一个组件。

    • [强制]高阶组件使用camelCase命名。

      高阶组件事实上并非一个组件,而是一个“生成组件类型”的函数,因此遵守JavaScript函数命名的规范,使用camelCase命名。

    • [强制]使用onXxx形式作为props中用于回调的属性名称。

      使用统一的命名规则用以区分props中回调和非回调部分的属性,在JSX上可以清晰地看到一个组件向上和向下的逻辑交互。

      对于不用于回调的函数类型的属性,使用动词作为属性名称。

    • [建议]使用withXxxxxxable形式的词作为高阶组件的名称。

      高阶组件是为组件添加行为和功能的函数,因此使用如上形式的词有助于对其功能进行理解。

    • [建议]作为组件方法的事件处理函数以具备业务含义的词作为名称,不使用onXxx形式命名。

      1. // Good
      2. class Form {
      3. @autobind
      4. collectAndSubmitData() {
      5. let data = {
      6. name: this.state.name,
      7. age: this.state.age
      8. };
      9. this.props.onSubmit(data);
      10. }
      11. syncName() {
      12. // ...
      13. }
      14. @autobind
      15. syncAge() {
      16. // ...
      17. }
      18. render() {
      19. return (
      20. <div>
      21. <label>姓名:<input type="text" onChange={this.syncName} /></label>
      22. <label>年龄:<input type="number" onChange={this.syncAge} /></label>
      23. <button type="button" onClick={this.collectAndSubmit}>提交</button>
      24. </div>
      25. );
      26. }
      27. }
    • [强制]使用ES Class声明组件,禁止使用React.createClass

      已经弃用了React.createClass函数。

      1. // Bad
      2. let Message = React.createClass({
      3. render() {
      4. return <span>{this.state.message}</span>;
      5. }
      6. });
      7. // Good
      8. class Message extends PureComponent {
      9. render() {
      10. return <span>{this.state.message}</span>;
      11. }
      12. }
    • [强制]不使用state的组件声明为函数组件。

      1. // Bad
      2. class NextNumber {
      3. render() {
      4. return <span>{this.props.value + 1}</span>
      5. }
      6. }
      7. // Good
      8. let NextNumber = ({value}) => <span>{value + 1}</span>;
    • [强制]所有组件均需声明propTypes

      propsTypes在提升组件健壮性的同时,也是一种类似组件的文档的存在,有助于代码的阅读和理解。

    • [强制]对于所有非isRequired的属性,在defaultProps中声明对应的值。

      声明初始值有助于对组件初始状态的理解,也可以减少propTypes对类型进行校验产生的开销。

      对于初始没有值的属性,应当声明初始值为null而非undefined

    • [强制]如无必要,使用静态属性语法声明propsTypescontextTypesdefaultPropsstate

      仅当初始state需要从props计算得到的时候,才将state的声明放在构造函数中,其它情况下均使用静态属性声明进行。

    • [强制]依照规定顺序编排组件中的方法和属性。

      按照以下顺序编排组件中的方法和属性:

      1. static displayName
      2. static propTypes
      3. static contextTypes
      4. state defaultProps
      5. static state
      6. 其它静态的属性
      7. 用于事件处理并且以属性的方式(onClick = e => {...})声明的方法
      8. 其它实例属性
      9. constructor
      10. getChildContext
      11. componentWillMount
      12. componentDidMount
      13. shouldComponentUpdate
      14. componentDidUpdate
      15. componentWillUnmount
      16. 事件处理方法
      17. 其它方法
      18. render

        其中shouldComponentUpdaterender是一个组件最容易被阅读的函数,因此放在最下方有助于快速定位。

    • [建议]无需显式引入React对象。

      使用JSX隐式地依赖当前环境下有React这一对象,但在源码上并没有显式使用,这种情况下添加会造成一个没有使用的变量存在。

      使用babel-plugin-react-require插件可以很好地解决这一问题,因此无需显式地编写import React from 'react';这一语句。

    • [建议]使用箭头函数声明函数组件。

      箭头函数具备更简洁的语法(无需function关键字),且可以在仅有一个语句时省去return造成的额外缩进。

    • [建议]高阶组件返回新的组件类型时,添加displayName属性。

      同时在displayName上声明高阶组件的存在。

      1. // Good
      2. let asPureComponent = Component => {
      3. let componentName = Component.displayName || Component.name || 'UnknownComponent';
      4. return class extends PureComponent {
      5. static displayName = `asPure(${componentName})`
      6. render() {
      7. return <Component {..this.props} />;
      8. }
      9. };
      10. };
    • [强制]除顶层或路由级组件以外,所有组件均在概念上实现为纯组件(Pure Component)。

      本条规则并非要求组件继承自PureComponent,“概念上的纯组件”的意思为一个组件在propsstate没有变化(shallowEqual)的情况下,渲染的结果应保持一致,即shouldComponentUpdate应当返回false

      一个典型的非纯组件是使用了随机数或日期等函数:

      1. let RandomNumber = () => <span>{Math.random()}</span>;
      2. let Clock = () => <span>{Date.time()}</span>;

      非纯组件具备向上的“传染性”,即一个包含非纯组件的组件也必须是非纯组件,依次沿组件树结构向上。由于非纯组件无法通过shouldComponentUpdate优化渲染性能且具备传染性,因此要避免在非顶层或路由组件中使用。

      如果需要在组件树的某个节点使用随机数、日期等非纯的数据,应当由顶层组件生成这个值并通过props传递下来。对于使用Redux等应用状态管理的系统,可以在应用状态中存放相关值(如Redux使用Action Creator生成这些值并通过Action和reducer更新到store中)。

    • [强制]禁止为继承自PureComponent的组件编写shouldComponentUpdate实现。

      参考,在React的实现中,PureComponent并不直接实现shouldComponentUpdate,而是添加一个isReactPureComponent的标记,由CompositeComponent通过识别这个标记实现相关的逻辑。因此在PureComponent上自定义shouldComponentUpdate并无法享受super.shouldComponentUpdate的逻辑复用,也会使得这个继承关系失去意义。

    • shouldComponentUpdate方法在React的性能中扮演着至关重要的角色,纯组件必定能通过propsstate的变化来决定是否进行渲染,因此如果组件为纯组件且不继承shouldComponentUpdate,则应当有自己的shouldComponentUpdate实现来减少不必要的渲染。

    • [建议]为函数组件添加PureComponent能力。

      函数组件并非一定是纯组件,因此其shouldComponentUpdate的实现为return true;,这可能导致额外的无意义渲染,因此推荐使用高阶组件为其添加shouldComponentUpdate的相关逻辑。

      推荐使用react-pure-stateless-component库实现这一功能。

    • [建议]使用@autobind进行事件处理方法与this的绑定。

      由于PureComponent使用进行是否渲染的判断,如果在JSX中使用bind或箭头函数绑定this会造成子组件每次获取的函数都是一个新的引用,这破坏了shouldComponentUpdate的逻辑,引入了无意义的重复渲染,因此需要在render调用之前就将事件处理方法与this绑定,在每次render`调用中获取同样的引用。

      当前比较流行的事前绑定this的方法有2种,其一使用类属性的语法:

      其二使用的装饰器:

      1. class Foo {
      2. @autobind
      3. onClick(e) {
      4. // ...
      5. }
      6. }

      使用类属性语法虽然可以避免引入一个autobind的实现,但存在一定的缺陷:

      1. 对于新手不容易理解函数内的this的定义。
      2. 无法在函数是使用其它的装饰器(如memoizedeprecated或检验相关的逻辑等)。

        因此,推荐使用装饰器实现this的事先绑定,推荐使用core-decorators库提供的相关装饰器实现。

    • [强制]没有子节点的非DOM组件使用自闭合语法。

      对于DOM节点,按照HTML编码规范相关规则进行闭合,其中void element使用自闭合语法

      1. // Bad
      2. <Foo></Foo>
      3. // Good
      4. <Foo />
    • [强制]保持起始和结束标签在同一层缩进。

      对于标签前面有其它语句(如return的情况,使用括号进行换行和缩进)。

      1. // Bad
      2. class Message {
      3. render() {
      4. return <div>
      5. <span>Hello World</span>
      6. </div>;
      7. }
      8. }
      9. // Good
      10. class Message {
      11. render() {
      12. return (
      13. <div>
      14. <span>Hello World</span>
      15. </div>;
      16. );
      17. }
      18. }

      对于直接return的函数组件,可以直接使用括号而省去大括号和return关键字:

      1. let Message = () => (
      2. <div>
      3. <span>Hello World</span>
      4. </div>
      5. );
    • [强制]对于多属性需要换行,从第一个属性开始,每个属性一行。

      1. // 没有子节点
      2. <SomeComponent
      3. longProp={longProp}
      4. anotherLongProp={anotherLongProp}
      5. />
      6. <SomeComponent
      7. longProp={longProp}
      8. anotherLongProp={anotherLongProp}
      9. >
      10. <SomeChild />
      11. <SomeChild />
      12. </SomeComponent>
    • [强制]以字符串字面量作为值的属性使用双引号("),在其它类型表达式中的字符串使用单引号(')。

    • [强制]自闭合标签的/>前添加一个空格。

      1. // Bad
      2. <Foo bar="bar"/>
      3. <Foo bar="bar" />
      4. // Good
    • [强制]对于值为true的属性,省去值部分。

      1. // Bad
      2. <Foo visible={true} />
      3. // Good
      4. <Foo visible />
    • [强制]对于需要使用key的场合,提供一个唯一标识作为key属性的值,禁止使用可能会变化的属性(如索引)。

      key属性是React在进行列表更新时的重要属性,如该属性会发生变化,渲染的性能和正确性都无法得到保证。

      1. // Bad
      2. {list.map((item, index) => <Foo key={index} {...item} />)}
      3. // Good
      4. {list.map(item => <Foo key={item.id} {...item} />)}
    • [建议]避免在JSX的属性值中直接使用对象和函数表达式。

      PureComponent使用对propsstate进行比较来决定是否需要渲染,而在JSX的属性值中使用对象、函数表达式会造成每一次的对象引用不同,从而shallowEqual会返回false,导致不必要的渲染。

    1. ```javascript
    2. // Bad
    3. class WarnButton {
    4. alertMessage(message) {
    5. alert(message);
    6. }
    7. render() {
    8. return <button type="button" onClick={() => this.alertMessage(this.props.message)}>提示</button>
    9. }
    10. }
    11. // Good
    12. class WarnButton {
    13. @autobind
    14. alertMessage() {
    15. alert(this.props.message);
    16. }
    17. render() {
    18. return <button type="button" onClick={this.alertMessage}>提示</button>
    19. }
    20. }
    21. ```
    • [建议]将JSX的层级控制在3层以内。

      1. // Bad
      2. let List = ({items}) => (
      3. <ul>
      4. {
      5. items.map(item => (
      6. <li>
      7. <header>
      8. <h3>{item.title}</h3>
      9. <span>{item.subtitle}</span>
      10. </header>
      11. <section>{item.content}</section>
      12. <footer>
      13. <span>{item.author}</span>@<time>{item.postTime}</time>
      14. </footer>
      15. </li>
      16. ))
      17. }
      18. </ul>
      19. );
      20. // Good
      21. let Header = ({title, subtitle}) => (
      22. <header>
      23. <h3>{title}</h3>
      24. <span>{subtitle}</span>
      25. </header>
      26. );
      27. let Content = ({content}) => <section>{content}</section>;
      28. let Footer = ({author, postTime}) => (
      29. <footer>
      30. <span>{author}</span>@<time>{postTime}</time>
      31. </footer>
      32. );
      33. let Item = item => (
      34. <div>
      35. <Header {...item} />
      36. <Content {...item} />
      37. <Footer {...item} />
      38. </div>
      39. );
      40. let List = ({items}) => (
      41. <ul>
      42. {items.map(Item)}
      43. );