牛骨文教育服务平台(让学习变的简单)

方法顺序遵循生命周期放在前面, render() 方法放在最后

在 react 组件内部,方法的顺序如下:

  1. 生命周期方法(按照时间先后顺序依次为: getDefaultPropsgetInitialStatecomponentWillMount,componentDidMountcomponentWillReceivePropsshouldComponentUpdatecomponentWillUpdate,componentDidUpdatecomponentWillUnmount )

  2. 其他的方法

  3. render 方法

事件处理函数的命名

采用 "handle" + "EventName" 的方式来命名
Example:

<Component onClick={this.handleClick} onLaunchMissiles={this.handleLaunchMissiles} />

事件函数作为属性时的命名

为了跟 react 的事件命名保持一致: onClickonDragonChange, 等等,采用如下格式:

<Component onLaunchMissiles={this.handleLaunchMissiles} />

元素跟 return 放在同一行

为了节约空间,采用下面的写法:

return <div>
    ...
</div>;

而不是:

return (      // "div" 与 "return" 不在同一行
    <div>
        ...
    </div>
);

对HTML的属性进行对齐和排序

如果属性不是太多,那就放在同一行,否则就把每一个属性都单独写一行:

<div className="highlight" key="highlight-div">
<div
    className="highlight"
    key="highlight-div"
>
<Image
    className="highlight"
    key="highlight-div"
/>

而不是:

<div className="highlight"      // 属性没有在单独行
     key="highlight-div"
>
<div                            // 闭合便签不在单独的行
    className="highlight"
    key="highlight-div">
<div                            // 属性没有排序(一般重要的属性写在前面)
    key="highlight-div"
    className="highlight"
>

一个文件只导出一个 react 类

每一个 .jsx 应该只能导出单独的 react 类。这样有利于测试,因为这些测试框架要求一个文件导出的就是一个函数。
注意:你依然可以在一个文件中定义多个类,只要保证导出的只有一个即可。