Airbnb React/JSX 编码规范

Airbnb React/JSX 编码规范

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

内容目录

  1. 基本规范
  2. Class vs React.createClass vs stateless
  3. 命名
  4. 声明模块
  5. 代码对齐
  6. 单引号还是双引号
  7. 空格
  8. 属性
  9. Refs引用
  10. 括号
  11. 标签
  12. 函数/方法
  13. 模块生命周期
  14. isMounted

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

      // badconst Listing = React.createClass({
        // ...render() {
          return <div>{this.state.hello}</div>;}});  // goodclass Listing extends React.Component {
        // ...render() {
          return <div>{this.state.hello}</div>;}}

    如果你的模块没有状态或是没有引用refs, 推荐使用普通函数(非箭头函数)而不是类:

      // badclass Listing extends React.Component {render() {
          return <div>{this.props.hello}</div>;}}  // bad (relying on function name inference is discouraged)const Listing = ({ hello }) => (<div>{hello}</div>);  // goodfunction Listing({ hello }) {
        return <div>{hello}</div>;}

Naming 命名

  • 扩展名: React模块使用 .jsx 扩展名.
  • 文件名: 文件名使用驼峰式. 如, ReservationCard.jsx.
  • 引用命名: React模块名使用驼峰式命名,实例使用骆驼式命名. eslint: react/jsx-pascal-case

    // badimport reservationCard from './ReservationCard';// goodimport ReservationCard from './ReservationCard';// badconst ReservationItem = <ReservationCard />;// goodconst reservationItem = <ReservationCard />;
  • 模块命名: 模块使用当前文件名一样的名称. 比如 ReservationCard.jsx 应该包含名为 ReservationCard的模块. 但是,如果整个文件夹是一个模块,使用 index.js作为入口文件,然后直接使用 index.js 或者文件夹名作为模块的名称:

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

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

      // bad  export default function withFoo(WrappedComponent) {
        return function WithFoo(props) {
          return <WrappedComponent {...props} foo />;}}  // good  export default function withFoo(WrappedComponent) {function WithFoo(props) {
          return <WrappedComponent {...props} foo />;}const wrappedComponentName = WrappedComponent.displayName      || WrappedComponent.name      || 'Component';WithFoo.displayName = `withFoo(${wrappedComponentName})`;
        return WithFoo;}
  • 属性命名: 避免使用DOM相关的属性来用作其他的用途。

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

      // bad<MyComponent style="fancy" />  // good<MyComponent variant="fancy" />

Declaration 声明模块

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

    // badexport default React.createClass({
      displayName: 'ReservationCard',
      // stuff goes here
    });// goodexport default class ReservationCard extends React.Component {
    }

Alignment 代码对齐

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

    // bad
    <Foo superLongParam="bar"anotherSuperLongParam="baz" />// good, 有多行属性的话, 新建一行关闭标签
    <FoosuperLongParam="bar"anotherSuperLongParam="baz"
    />// 若能在一行中显示, 直接写成一行
    <Foo bar="bar" />// 子元素按照常规方式缩进
    <FoosuperLongParam="bar"anotherSuperLongParam="baz"
    ><Quux />
    </Foo>

Quotes 单引号还是双引号

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

    为什么? JSX属性 不能包括转译的引号, 因此在双引号里包括像 "don't" 的属性值更容易输入. HTML属性也是用双引号,所以JSX属性也遵循同样的语法.

      // bad<Foo bar='bar' />  // good<Foo bar="bar" />  // bad<Foo style={{ left: "20px" }} />  // good<Foo style={{ left: '20px' }} />

Spacing 空格

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

    // bad
    <Foo/>// very bad
    <Foo                 />// bad
    <Foo/>// good
    <Foo />
  • 不要在JSX {} 引用括号里两边加空格. eslint: react/jsx-curly-spacing

    // bad
    <Foo bar={ baz } />// good
    <Foo bar={baz} />

Props 属性

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

    // bad
    <FooUserName="hello"phone_number={12345678}
    />// good
    <FoouserName="hello"phoneNumber={12345678}
    />
  • 如果属性值为 true, 可以直接省略. eslint: react/jsx-boolean-value

    // bad
    <Foohidden={true}
    />// good
    <Foohidden
    />
  • <img> 标签总是添加 alt 属性. 如果图片以presentation(感觉是以类似PPT方式显示?)方式显示,alt 可为空, 或者<img> 要包含role="presentation". eslint: jsx-a11y/img-has-alt

    // bad
    <img src="hello.jpg" />// good
    <img src="hello.jpg" alt="Me waving hello" />// good
    <img src="hello.jpg" alt="" />// good
    <img src="hello.jpg" role="presentation" />
  • 不要在 alt 值里使用如 "image", "photo", or "picture"包括图片含义这样的词, 中文也一样. eslint: jsx-a11y/img-redundant-alt

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

      // bad<img src="hello.jpg" alt="Picture of me waving hello" />  // good<img src="hello.jpg" alt="Me waving hello" />
  • 使用有效正确的 aria role属性值 ARIA roles. eslint: jsx-a11y/aria-role

    // bad - not an ARIA role
    <div role="datepicker" />// bad - abstract ARIA role
    <div role="range" />// good
    <div role="button" />
  • 不要在标签上使用 accessKey 属性. eslint: jsx-a11y/no-access-key

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

    // bad
    <div accessKey="h" />// good
    <div />
  • 避免使用数组的index来作为属性key的值,推荐使用唯一ID. (为什么?)

    // bad
    {todos.map((todo, index) =><Todo{...todo}key={index}/>
    )}// good
    {todos.map(todo => (<Todo{...todo}key={todo.id}/>
    ))}

Refs

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

    // bad
    <Fooref="myRef"
    />// good
    <Fooref={ref => { this.myRef = ref; }}
    />

Parentheses 括号

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

    // badrender() {
      return <MyComponent className="long body" foo="bar"><MyChild /></MyComponent>;
    }// goodrender() {
      return (<MyComponent className="long body" foo="bar"><MyChild /></MyComponent>);
    }// good, 单行可以不需要render() {const body = <div>hello</div>;
      return <MyComponent>{body}</MyComponent>;
    }

Tags 标签

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

    // bad
    <Foo className="stuff"></Foo>// good
    <Foo className="stuff" />
  • 如果模块有多行的属性, 关闭标签时新建一行. eslint: react/jsx-closing-bracket-location

    // bad
    <Foobar="bar"baz="baz" />// good
    <Foobar="bar"baz="baz"
    />

Methods 函数

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

    function ItemList(props) {
      return (<ul>{props.items.map((item, index) => (        <Item          key={item.key}          onClick={() => doSomethingWith(item.name, index)}        />      ))}</ul>);
    }
  • 当在 render() 里使用事件处理方法时,提前在构造函数里把 this 绑定上去. eslint: react/jsx-no-bind

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

      // badclass extends React.Component {onClickDiv() {
          // do stuff}render() {
          return <div onClick={this.onClickDiv.bind(this)} />}}  // goodclass extends React.Component {constructor(props) {super(props);      this.onClickDiv = this.onClickDiv.bind(this);}onClickDiv() {
          // do stuff}render() {
          return <div onClick={this.onClickDiv} />}}
  • 在React模块中,不要给所谓的私有函数添加 _ 前缀,本质上它并不是私有的.

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

      // badReact.createClass({_onClickSubmit() {
          // do stuff},    // other stuff});  // goodclass extends React.Component {onClickSubmit() {
          // do stuff}    // other stuff}
  • 在 render 方法中总是确保 return 返回值. eslint: react/require-render-return

    // badrender() {(<div />);
    }// goodrender() {
      return (<div />);
    }

Ordering React 模块生命周期

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

  1. 可选的 static 方法
  2. constructor 构造函数
  3. getChildContext 获取子元素内容
  4. componentWillMount 模块渲染前
  5. componentDidMount 模块渲染后
  6. componentWillReceiveProps 模块将接受新的数据
  7. shouldComponentUpdate 判断模块需不需要重新渲染
  8. componentWillUpdate 上面的方法返回 true, 模块将重新渲染
  9. componentDidUpdate 模块渲染结束
  10. componentWillUnmount 模块将从DOM中清除, 做一些清理任务
  11. 点击回调或者事件处理器 如 onClickSubmit() 或 onChangeDescription()
  12. render 里的 getter 方法 如 getSelectReason() 或 getFooterContent()
  13. 可选的 render 方法 如 renderNavigation() 或 renderProfilePicture()
  14. render render() 方法

  • 如何定义 propTypesdefaultPropscontextTypes, 等等其他属性...

    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 <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>}
    }Link.propTypes = propTypes;
    Link.defaultProps = defaultProps;export default Link;
  • React.createClass 的生命周期函数,与使用class稍有不同: eslint: react/sort-comp

  1. displayName 设定模块名称
  2. propTypes 设置属性的类型
  3. contextTypes 设置上下文类型
  4. childContextTypes 设置子元素上下文类型
  5. mixins 添加一些mixins
  6. statics
  7. defaultProps 设置默认的属性值
  8. getDefaultProps 获取默认属性值
  9. getInitialState 或者初始状态
  10. getChildContext
  11. componentWillMount
  12. componentDidMount
  13. componentWillReceiveProps
  14. shouldComponentUpdate
  15. componentWillUpdate
  16. componentDidUpdate
  17. componentWillUnmount
  18. clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
  19. getter methods for render like getSelectReason() or getFooterContent()
  20. Optional render methods like renderNavigation() or renderProfilePicture()
  21. render

isMounted

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

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

⬆ 回到顶部


来源: https://github.com/JasonBoy/javascript/tree/master/react


来自为知笔记(Wiz)


转载于:https://www.cnblogs.com/itlyh/p/6020648.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/457033.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Mysql数据库使用总结

mysql数据库使用总结 本文主要记录一些mysql日常使用的命令&#xff0c;供以后查询。 1.更改root密码 mysqladmin -uroot password yourpassword 2.远程登陆mysql服务器 mysql -uroot -p -h192.168.137.10 -P3306 3.查询数据库 show databases; 4.进入某个数据库 use databa…

c语言递归汉诺塔次数,汉诺塔问题(C语言经典递归问题(一))

把A杆上的金盘全部移到C杆上&#xff0c;并仍保持原有顺序叠好。操作规则&#xff1a;每次只能移动一个盘子&#xff0c;并且在移动过程中三根杆上都始终保持大盘在下&#xff0c;小盘在上&#xff0c;操作过程中盘子可以置于A、B、C任一杆上。思路&#xff1a;图解&#xff1a…

Eclipes导入的项目中的中文都是乱码的解决办法

把项目导入Eclipse时&#xff0c;里边的中文全是乱码&#xff0c;试了很多方法&#xff0c;最终总结一下&#xff01; eclipse之所以会出现乱码问题是因为eclipse编辑器选择的编码规则是可变的。一般默认都是UTF-8或者GBK&#xff0c;当从外部导入的一个工程时&#xff0c;如果…

理解浏览器是如何加载及渲染网页的

先上图&#xff0c;我们再慢慢解释&#xff0c;这图就是浏览器加载网页的一个过程 当我们在浏览器输入一个地址&#xff08;比如:http://toadw.cn&#xff09;,那么点击回车后&#xff0c;浏览器是如何加载网页的呢&#xff1f; 加载过程 一开始浏览器是不知道你输入的http://t…

CentOS下的Mysql的安装和使用

1.使用安装命令 &#xff1a;yum -y install mysql mysql-server mysql-devel 安装完成却发现Myserver安装缺失&#xff0c;在网上找原因&#xff0c;原来是因为CentOS 7上把MySQL从默认软件列表中移除了&#xff0c;用MariaDB来代替&#xff0c;所以这导致我们必须要去官网上…

NOIP模拟题——神秘大门

【题目描述】最近小K大牛经过调查发现&#xff0c;在WZland的最南方——WZ Antarctica 出现了奇怪的磁场反应。为了弄清楚这一现象&#xff0c;小K 大牛亲自出马&#xff0c;来到了WZ Antarctica。小K大牛发现WZ Antarctica 出现了一道神秘的大门。人总有好奇心&#xff0c;小K…

大学c语言程序设计大赛,关于举办宁夏大学第二届C语言程序设计大赛的通知

各学院&#xff1a;根据学校《关于进一步加强基础课教学改革的意见》(宁大校发〔2008〕178号)、《关于加强学生创新精神和创新能力培养的实施意见》(宁大校发〔2008〕75号)的有关文件精神&#xff0c;经研究决定举办宁夏大学第二届C语言程序设计大赛&#xff0c;从中选拔出优秀…

Android中创建自己的对话框

Activities提供了一种方便管理的创建、保存、回复的对话框机制&#xff0c;例如 onCreateDialog(int), onPrepareDialog(int, Dialog), showDialog(int), dismissDialog(int)等方法&#xff0c;如果使用这些方法的话&#xff0c;Activity将通过getOwnerActivity()方法返回该Act…

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11

搭建Django2.0Python3MySQL5时同步数据库时报错&#xff1a; django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None 解决办法&#xff1a; 找到Python安装路劲下的Python36-32\Lib\site-packages\django\db\backend…

一件很好笑的事情

我是一个比较习惯努力学习的人&#xff0c; 我也会去学习各种可能与我有交集的知识&#xff0c; 就在这几天&#xff0c;我看到以前的一个android网络培训学校开办了C/C的培训&#xff0c;这是挺好的事&#xff0c; 但是看他们的文件&#xff0c;我就奇怪了。 这份文件&#xf…

c语言实现循环链表,c语言实现循环链表的基本操作

循环链表和单链表其实区别不大,差别仅在于算法中的循环条件不是p或者p->next,而是是否等于头指针。下面这个例子简单的实现了循环链表的基本操作,其中插入和删除只是完成了主要的部分,没有判断。#include#includestruct Data{char name;int age;};struct CirList{Data *data…

关于Eclipes的Logcat无法打印消息的解决办法

转自&#xff1a;http://blog.csdn.net/harry211/article/details/8453532 调试程序需要打印一些消息出来&#xff0c;logcat不好用的话就很麻烦了。这个问题折腾了好久&#xff0c;为啥就是不出来呢&#xff1f; 上网找了很多解决办法&#xff1a; 重启eclipse 重启adb 重启…

17:文字排版

17:文字排版 查看提交统计提问总时间限制: 1000ms内存限制: 65536kB描述给一段英文短文&#xff0c;单词之间以空格分隔&#xff08;每个单词包括其前后紧邻的标点符号&#xff09;。请将短文重新排版&#xff0c;要求如下&#xff1a; 每行不超过80个字符&#xff1b;每个单词…

解决AttributeError: 'str' object has no attribute 'decode'报错问题

顺着报错文件点进去&#xff0c;找到query query.decode(errors‘replace’) 将decode修改为encode即可

c语言指针数组课件,C语言指针与数组教程课件.ppt

C语言指针与数组教程;教学要求;本章主要内容;引子;#include void swap ( int x, int y ) { printf("调用时&#xff1a;x地址为&#xff1a;%p, 值为&#xff1a;%d\n",&x,x); printf("调用时&#xff1a;y地址为&#xff1a;%p, 值为&#xff1a;%d\n"…

Android控制EditText的焦点

在项目中&#xff0c;一进入一个页面, EditText默认就会自动获取焦点。 那么如何取消这个默认行为呢&#xff1f; 在网上找了好久&#xff0c;有点 监听软键盘事件&#xff0c;有点 调用 clearFouse()方法&#xff0c;但是测试了都没有&#xff01; xml中也找不到相应的属性可以…

解决python中html 代码被注释掉 依旧被解释导致报错ERROR:tornado.access:500 GET /home (xxx.xxx.xxx.xxx)

ERROR:tornado.access:500 GET /home (xxx.xxx.xxx.xxx) 注释的是Html代码&#xff0c;是给浏览器看的。 Html里的代码还是要执行。注释python代码用{# #}

springMvc 传子 bean 中有bean

2019独角兽企业重金招聘Python工程师标准>>> bean 类型 如下 1. json 字符串 $.ajax({ url :${ctx}/test/testData/f1?bookjava, type: post, dataType : "json", con…

通过rsync搭建一个远程备份系统(二)

Rsyncinotify实时备份数据 rsync在同步数据的时候&#xff0c;需要扫描所有文件后进行对比&#xff0c;然后进行差量传输&#xff0c;如果文件达到了百万或者千万级别以上是&#xff0c;扫描文件的时间也很长&#xff0c;而如果只有少量的文件变更了&#xff0c;那么此时rsync是…

C语言扫地雷游戏的题目简介,C语言程序设计课程设计(论文)-扫地雷游戏.doc...

C语言程序设计课程设计(论文)-扫地雷游戏辽 宁 工 业 大 学C语言程序设计 课程设计(论文)题目&#xff1a; 扫地雷游戏院(系)&#xff1a; 软件学院专业班级: 电子商务091班学 号:学生姓名&#xff1a;指导教师&#xff1a;教师职称&#xff1a; 助 教起止时间&#xff1a;2009…