资讯专栏INFORMATION COLUMN

Airbnb React/JSX 编码规范

CODING / 3275人阅读

摘要:来自于中文编码规范编码规范算是最合理的编码规范之一了基本规范每个文件只写一个模块但是多个无状态模块可以放在单个文件中推荐使用语法不要使用,除非从一个非的文件中初始化你的创建模块如果你的模块有内部状态或者是推荐使用而不是除非你有充足的理由

来自于Airbnb React/JSX 中文编码规范

Airbnb React/JSX 编码规范

算是最合理的React/JSX编码规范之一了

Basic Rules 基本规范

每个文件只写一个模块.

但是多个无状态模块可以放在单个文件中. eslint: react/no-multi-comp.

推荐使用JSX语法.

不要使用 React.createElement,除非从一个非JSX的文件中初始化你的app.

创建模块

Class vs React.createClass vs stateless

如果你的模块有内部状态或者是refs, 推荐使用 class extends React.Component 而不是 React.createClass ,除非你有充足的理由来使用这些方法.
eslint: react/prefer-es6-class react/prefer-stateless-function

// bad
const Listing = React.createClass({
  // ...
  render() {
    return 
{this.state.hello}
; } }); // good class Listing extends React.Component { // ... render() { return
{this.state.hello}
; } }
如果你的模块没有状态或是没有引用`refs`, 推荐使用普通函数(非箭头函数)而不是类:
// bad
class Listing extends React.Component {
  render() {
    return 
{this.props.hello}
; } } // bad (relying on function name inference is discouraged) const Listing = ({ hello }) => (
{hello}
); // good function Listing({ hello }) { return
{hello}
; }
Naming 命名

扩展名: React模块使用 .jsx 扩展名.
 - 文件名: 文件名使用帕斯卡命名. 如, ReservationCard.jsx.

 - 引用命名: React模块名使用帕斯卡命名,实例使用骆驼式命名. eslint: react/jsx-pascal-case

// bad
import reservationCard from "./ReservationCard";

// good
import ReservationCard from "./ReservationCard";

// bad
const ReservationItem = ;

// good
const reservationItem = ;

模块命名: 模块使用当前文件名一样的名称. 比如 ReservationCard.jsx 应该包含名为 ReservationCard的模块. 但是,如果整个文件夹是一个模块,使用 index.js作为入口文件,然后直接使用 index.js 或者文件夹名作为模块的名称:

// bad
import Footer from "./Footer/Footer";

// bad
import Footer from "./Footer/index";

// good
import Footer from "./Footer";

高阶模块命名: 对于生成一个新的模块,其中的模块名 displayName 应该为高阶模块名和传入模块名的组合. 例如, 高阶模块 withFoo(), 当传入一个 Bar 模块的时候, 生成的模块名 displayName 应该为 withFoo(Bar).

为什么?一个模块的 displayName 可能会在开发者工具或者错误信息中使用到,因此有一个能清楚的表达这层关系的值能帮助我们更好的理解模块发生了什么,更好的Debug.

// bad
export default function withFoo(WrappedComponent) {
  return function WithFoo(props) {
    return ;
  }
}

// good
export default function withFoo(WrappedComponent) {
  function WithFoo(props) {
    return ;
  }

  const wrappedComponentName = WrappedComponent.displayName
    || WrappedComponent.name
    || "Component";

  WithFoo.displayName = `withFoo(${wrappedComponentName})`;
  return WithFoo;
}

属性命名: 避免使用DOM相关的属性来用作其他的用途。

为什么?对于styleclassName这样的属性名,我们都会默认它们代表一些特殊的含义,如元素的样式,CSS class的名称。在你的应用中使用这些属性来表示其他的含义会使你的代码更难阅读,更难维护,并且可能会引起bug。

// bad


// good
Declaration 声明模块

不要使用 displayName 来命名React模块,而是使用引用来命名模块, 如 class 名称.

// bad
export default React.createClass({
  displayName: "ReservationCard",
  // stuff goes here
});

// good
export default class ReservationCard extends React.Component {
}

Alignment 代码对齐

遵循以下的JSX语法缩进/格式. eslint: react/jsx-closing-bracket-location

// bad


// good, 有多行属性的话, 新建一行关闭标签


// 若能在一行中显示, 直接写成一行


// 子元素按照常规方式缩进

  

Quotes 单引号还是双引号

对于JSX属性值总是使用双引号("), 其他均使用单引号("). eslint: jsx-quotes

为什么? HTML属性也是用双引号, 因此JSX的属性也遵循此约定.

// bad


// good


// bad


// good
Spacing 空格

总是在自动关闭的标签前加一个空格,正常情况下也不需要换行. eslint: no-multi-spaces, react/jsx-space-before-closing

// bad


// very bad


// bad


// good

不要在JSX {} 引用括号里两边加空格. eslint: react/jsx-curly-spacing

// bad


// good

Props 属性

JSX属性名使用骆驼式风格camelCase.

// bad


// good

如果属性值为 true, 可以直接省略. eslint: react/jsx-boolean-value

// bad

// good // good // good

不要在 alt 值里使用如 "image", "photo", or "picture"包括图片含义这样的词, 中文也一样. eslint: jsx-a11y/img-redundant-alt

为什么? 屏幕助读器已经把 img 标签标注为图片了, 所以没有必要再在 alt 里说明了.

// bad


// good

使用有效正确的 aria role属性值 ARIA roles. eslint: jsx-a11y/aria-role

// bad - not an ARIA role
// bad - abstract ARIA role
// good

不要在标签上使用 accessKey 属性. eslint: jsx-a11y/no-access-key

为什么? 屏幕助读器在键盘快捷键与键盘命令时造成的不统一性会导致阅读性更加复杂.

// bad
// good

避免使用数组的index来作为属性key的值,推荐使用唯一ID. (为什么?)

// bad
{todos.map((todo, index) =>
  
)}

// good
{todos.map(todo => (
  
))}

对于所有非必须的属性,总是手动去定义defaultProps属性.

为什么? propTypes 可以作为模块的文档说明, 并且声明 defaultProps 的话意味着阅读代码的人不需要去假设一些默认值。更重要的是, 显示的声明默认属性可以让你的模块跳过属性类型的检查.

// bad
function SFC({ foo, bar, children }) {
  return 
{foo}{bar}{children}
; } SFC.propTypes = { foo: PropTypes.number.isRequired, bar: PropTypes.string, children: PropTypes.node, }; // good function SFC({ foo, bar }) { return
{foo}{bar}
; } SFC.propTypes = { foo: PropTypes.number.isRequired, bar: PropTypes.string, }; SFC.defaultProps = { bar: "", children: null, };
Refs

总是在Refs里使用回调函数. eslint: react/no-string-refs

// bad


// good
 { this.myRef = ref; }}
/>

Parentheses 括号

将多行的JSX标签写在 ()里. eslint: react/wrap-multilines

// bad
render() {
return 
     
   ;
}

// good
render() {
return (
  

  
);
}

// good, 单行可以不需要
render() {
const body = 
hello
; return {body}; }

Tags 标签

对于没有子元素的标签来说总是自己关闭标签. eslint: react/self-closing-comp

// bad


// good

如果模块有多行的属性, 关闭标签时新建一行. eslint: react/jsx-closing-bracket-location

// bad


// good

Methods 函数

使用箭头函数来获取本地变量.

function ItemList(props) {
  return (
    
    {props.items.map((item, index) => ( doSomethingWith(item.name, index)} /> ))}
); }

当在 render() 里使用事件处理方法时,提前在构造函数里把 this 绑定上去. eslint: react/jsx-no-bind

为什么? 在每次 render 过程中, 再调用 bind 都会新建一个新的函数,浪费资源.

// bad
class extends React.Component {
  onClickDiv() {
    // do stuff
  }

  render() {
    return 
} } // good class extends React.Component { constructor(props) { super(props); this.onClickDiv = this.onClickDiv.bind(this); } onClickDiv() { // do stuff } render() { return
} }

在React模块中,不要给所谓的私有函数添加 _ 前缀,本质上它并不是私有的.

为什么?_ 下划线前缀在某些语言中通常被用来表示私有变量或者函数。但是不像其他的一些语言,在JS中没有原生支持所谓的私有变量,所有的变量函数都是共有的。尽管你的意图是使它私有化,在之前加上下划线并不会使这些变量私有化,并且所有的属性(包括有下划线前缀及没有前缀的)都应该被视为是共有的。了解更多详情请查看Issue #1024, 和 #490 。

// bad
React.createClass({
  _onClickSubmit() {
    // do stuff
  },

  // other stuff
});

// good
class extends React.Component {
  onClickSubmit() {
    // do stuff
  }

  // other stuff
}

render 方法中总是确保 return 返回值. eslint: react/require-render-return

// bad
render() {
(
); } // good render() { return (
); }

Ordering React 模块生命周期

class extends React.Component 的生命周期函数:

可选的 static 方法

constructor 构造函数

getChildContext 获取子元素内容

componentWillMount 模块渲染前

componentDidMount 模块渲染后

componentWillReceiveProps 模块将接受新的数据

shouldComponentUpdate 判断模块需不需要重新渲染

componentWillUpdate 上面的方法返回 true, 模块将重新渲染

componentDidUpdate 模块渲染结束

componentWillUnmount 模块将从DOM中清除, 做一些清理任务

点击回调或者事件处理器onClickSubmit()onChangeDescription()

render 里的 getter 方法getSelectReason()getFooterContent()

可选的 render 方法renderNavigation()renderProfilePicture()

render render() 方法

如何定义 propTypes, defaultProps, contextTypes, 等等其他属性...

import React, { PropTypes } from "react";

const propTypes = {
  id: PropTypes.number.isRequired,
  url: PropTypes.string.isRequired,
  text: PropTypes.string,
};

const defaultProps = {
  text: "Hello World",
};

class Link extends React.Component {
  static methodsAreOk() {
    return true;
  }

  render() {
    return {this.props.text}
  }
}

Link.propTypes = propTypes;
Link.defaultProps = defaultProps;

export default Link;

React.createClass 的生命周期函数,与使用class稍有不同: eslint: react/sort-comp

displayName 设定模块名称

propTypes 设置属性的类型

contextTypes 设置上下文类型

childContextTypes 设置子元素上下文类型

mixins 添加一些mixins

statics

defaultProps 设置默认的属性值

getDefaultProps 获取默认属性值

getInitialState 或者初始状态

getChildContext

componentWillMount

componentDidMount

componentWillReceiveProps

shouldComponentUpdate

componentWillUpdate

componentDidUpdate

componentWillUnmount

clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()

getter methods for render like getSelectReason() or getFooterContent()

Optional render methods like renderNavigation() or renderProfilePicture()

render

isMounted

不要再使用 isMounted. eslint: react/no-is-mounted

为什么? isMounted 反人类设计模式:(), 在 ES6 classes 中无法使用, 官方将在未来的版本里删除此方法.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/86864.html

相关文章

  • React-CRA 应用中配合 VSCode 使用 ESLint 实践前端代码规范

    摘要:编码规范是独角兽公司内部的编码规范,该项目是上很受欢迎的一个开源项目,在前端开发中使用广泛,本文的配置规则就是以编码规范和编码规范作为基础的。 更新时间:2019-01-22React.js create-react-app 项目 + VSCode 编辑器 + ESLint 代码检查工具 + Airbnb 编码规范 前言 为什么要使用 ESLint 在项目开发过程中,编写符合团队编码规...

    Hujiawei 评论0 收藏0
  • 用eslint + prettier + pre-commit管理项目(React)

    摘要:前言人是很懒惰的,你刚开始建立的一个规规整整的项目,可能一段时间过后,就回被你无数次的提交代码弄得凌乱不堪。 前言 人是很懒惰的,你刚开始建立的一个规规整整的项目,可能一段时间过后,就回被你无数次的提交代码弄得凌乱不堪。就算你能保证你的编码风格严谨统一,别人又该如何,每个人都有不一样的编码风格,要保持统一,就要对项目进行适当的管理 正文 接下来介绍个React项目简单管理的一个实践: ...

    endiat 评论0 收藏0
  • React系列---ESlint

    摘要:是一个代码静态检查工具,可以检查的语法错误,提示潜在的,可以有效提高代码质量。维持前端团队高度一致的编码风格。 ESLint是一个JavaScript代码静态检查工具,可以检查JavaScript的语法错误,提示潜在的bug,可以有效提高代码质量。维持前端团队高度一致的编码风格。ESLint不但提供一些默认的规则,也提供用户自定义规则来约束所写的JavaScript代码。 详细的可以参...

    yanbingyun1990 评论0 收藏0
  • Sublime Text 3 搭建 React.js 开发环境

    摘要:有很强的自定义功能,插件库很庞大,针对新语言插件更新很快,配合使用可以快速搭建适配语言的开发环境。该命令依赖于包。源目录路径输出路径把所有东西放入缓存中,每次只编译修改过的文件发生错误时不会中断的流程,同时触发消息提示在命令行中输入运行。 Sublime有很强的自定义功能,插件库很庞大,针对新语言插件更新很快,配合使用可以快速搭建适配语言的开发环境。 1. babel-sublime ...

    Big_fat_cat 评论0 收藏0

发表评论

0条评论

CODING

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<