ES6 for React

更多请查看:https://github.com/mqy1023/react-with-es6/tree/master/00%E3%80%81es6-notes
一、语法基础
1、const和let
 a、相比es5的var是相对函数作用域范围,const和let都是相对块级作用域范围
 b、const定义后的变量不能再重新赋值

//ES6
const a = 1
let b = 'foo'
// a = 2 // Uncomment me!
// b = 'bar'
if (true) {
  const a = 3
}
//和上面同效果的ES5
'use strict';
var a = 1;
var b = 'foo';
// a = 2 // Uncomment me!
// b = 'bar'
if (true) {
  var _a = 3;//此次_a和a不一样,可见上面的es6的const是块级范围
}

2、箭头函数 =>

const foo = () => 'bar'

const baz = (x) => {
  return x + 1
}

const squareSum = (...args) => {
  const squared = args.map(x => Math.pow(x, 2))
  return squared.reduce((prev, curr) => prev + curr)
}

this.items.map(x => this.doSomethingWith(x))

经babel转译后同样效果的es5

use strict';
var foo = function foo() {
  return 'bar';
};

var baz = function baz(x) {
  return x + 1;
};

var squareSum = function squareSum() {
  for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  var squared = args.map(function (x) {
    return Math.pow(x, 2);
  });
  return squared.reduce(function (prev, curr) {
    return prev + curr;
  });
};

undefined.items.map(function (x) {
  return undefined.doSomethingWith(x);
});

3、Imports 和 Exports
 ES6自有模块化管理的Imports & Exports,相比之前使用module.exports = {…},我们可以 import & export多个name对应值
 每个文件可以有一个default默认的export,该默认值在另外文件import时可以不用带name来refer指定,其他非默认import时一定要指定name
  a、import导入

// 导入默认的export
import React from 'react-native'

// 导入非默认的exports
import {View, Text, Image} from 'react-native'

// 同时导入
import React, {View, Text, Image} from 'react-native'

  b、export导出

export default React
export {View, Text, Image}

React学习过程中ES6笔记收集

一、字符串中嵌入变量

var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
`String.raw`In ES5 "\n" is a line-feed.`

二、父组件传递props属性之…

<TodoApp todos={store.getState().todos}
    visibilityFilter={store.getState().visibilityFilter}/>
//ES6可写成
<TodoApp {...store.getState()} />

{ }的使用

const {todos, visibilityFilter} = this.props;
//相当于
const todos = this.props.todos;
const visibilityFilter = this.props.visibilityFilter;

三、省略return的写法

const concatFunc = (objA) => [...objA, 0];
//相当于
const concatFunc = (objA) => {
    return [...objA, 0];
}

四、传参时参数中默认值
1、ES6

const counter = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    default:
      return state;
  };
};

2 、ES5

'use strict';
var counter = function counter(state, action) {
  if (state === undefined) state = 0;

  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    default:
      return state;
  };
};

React Component with ES6

1、React 组件, propTypes 和 getDefaultTypes

class MyComponent extends React.Component {  
}

MyComponent.propTypes = {  
  someProp: React.PropTypes.string,
}

MyComponent.defaultProps = {  
  someProp: '',
}

2、ES6的class静态属性语法:(话说和Java几乎一模一样。。)

class MyComponent extends React.Component {  
  static propTypes = {
    someProp: React.PropTypes.string,
  };

  static defaultProps = {
    someProp: '',
  };
}

【注意】使用 static 语法需要在 Babel 配置中添加 stage-0。

{ "presets": ["stage-0"] }

3、getInitialState木有了,在constructor构造函数中初始化state,事件需在constructor中绑定

class MyComponent extends React.Component {  
  constructor(props) { //相当componentWillMount生命周期
    super(props);//使用能使用 this 关键字
    // 初始状态设置转移到 constructor 里了
    this.state = {
      someState: props.someProp,
    };
    this.handleClick = this.handleClick.bind(this);
  }
}

ES6 的继承机制实质是先创造父类的实例对象 this(所以必须先调用super 方法),然后再用子类的构造函数修改 this。
4、使用基类自动绑定

class BaseComponent extends React.Component {  
  _bind(...methods) {
    methods.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }
}

class MyComponent extends BaseComponent {  
  constructor() {
    super();
    this._bind('handleClick', 'handleFoo');
  }

  // ...
}

五、常用函数
1、filter过滤

let arrs = [1, 2, 3];
let a = arrs.filter((item) => item !== 2);
console.log(a);//[1, 3]

2、…xxx的使用
基础:push(& splice)和concat(& slice)的区别

push(& splice)在原object数组上操作,即会修改原object数组;
concat(& slice)不会修改原object数组,而是新建object数组后在该数组上操作

a、添加操作:push、concat、…
1、在原对象基础上copy新对象并添加一个key—value值

const userReducer = (state = {}) =>{
  return {
    ...state,
    name: 'TOM'
  };
};

let user = {id: 1, age: 23};
const userAfter = userReducer(user);
console.log(userAfter);
console.log(user);

//打印如下
[object Object] {
  age: 23,
  id: 1,
  name: "TOM"
}
[object Object] {
  age: 23,
  id: 1
}

jsbin运行地址:https://jsbin.com/hiteca/5/edit?html,js,console
2、push、concat、…

const objArr = [1, 2];//原数组
//*****
const concatFunc = (objA) => [...objA, 0];
//*****
console.log(concatFunc(objArr));//[1, 2, 0]

console.log(objArr.concat(3));//[1, 2, 3]

objArr.push(4);
console.log(objArr);//[1, 2, 4]

console.log(objArr.concat(5));//[1, 2, 4, 5]

//console控制台输出如下:
//[1, 2, 0]
//[1, 2, 3]
//[1, 2, 4]
//[1, 2, 4, 5]

jsbin运行地址:https://jsbin.com/pudozo/12/edit?js,console,output

b、删除操作:splice、slice、… :

const objArrB = [10, 20, 30];
//splice函数
const spileFunc = (objB, index) => {
  objB.splice(index, 1);
  return objB;
};
console.log(spileFunc(objArrB, 1));//[10, 30]
console.log(objArrB);//[10, 30]

const objArrC = [11, 22, 33];
//slice + concat函数
const scFunc = (objC, index) => {
  return objC.slice(0, index)
    .concat(objC.slice(index+1));

};

console.log(scFunc(objArrC, 1));//[11, 33]
console.log(objArrC);//[11, 22, 33]

const objArrD = [12, 23, 34];
//... + slice
//*****
const scdFunc = (objD, index) => {
  return [...objD.slice(0, index),
    ...objD.slice(index+1)];
};
//*****
console.log(scdFunc(objArrD, 1)); //[12, 34]
console.log(objArrD); //[12, 23, 34]

jsbin运行地址:https://jsbin.com/pudozo/37/edit?js,console,output
c、操作某个元素操作:… +slice :

const objList = [13, 24, 56];
//*****
const listFunc = (objList, index) => {
  return [...objList.slice(0, index),
          objList[index] + 1,
          ...objList.slice(index+1)
  ];
};
//*****

//让下标为1的元素加1
console.log(listFunc(objList, 1));
console.log(objList); 

jsbin运行地址:https://jsbin.com/yeyogih/1/edit?js,console,output

参考链接:
1、https://csspod.com/refactoring-react-components-to-es2015-classes/

2、https://facebook.github.io/react/docs/reusable-components.html#es6-classes

3、https://babeljs.io/blog/2015/06/07/react-on-es6-plus

4、http://www.cnblogs.com/rubylouvre/p/5025646.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个使用JS ES6React、antd和dva编写的类组件,可以根据传入的列名称和类型自动生成搜索框,每行最多显示三个框。下面是组件的示例代码: ```jsx import React from 'react'; import { Form, Input, Row, Col } from 'antd'; class SearchForm extends React.Component { renderSearchInputs = () => { const { searchColumns } = this.props; const searchInputs = []; for (let i = 0; i < searchColumns.length; i++) { const column = searchColumns[i]; const input = ( <Col span={8} key={i}> <Form.Item name={column.name} label={column.label}> {column.type === 'text' ? ( <Input placeholder={`请输入${column.label}`} /> ) : ( <Input.Search enterButton placeholder={`请输入${column.label}`} /> )} </Form.Item> </Col> ); searchInputs.push(input); } return searchInputs; }; render() { return ( <Form layout="vertical"> <Row gutter={16}>{this.renderSearchInputs()}</Row> </Form> ); } } export default SearchForm; ``` 在父组件中,你可以通过以下方式使用这个搜索框组件: ```jsx import React from 'react'; import SearchForm from './SearchForm'; class ParentComponent extends React.Component { searchColumns = [ { name: 'name', label: '姓名', type: 'text' }, { name: 'age', label: '年龄', type: 'number' }, { name: 'gender', label: '性别', type: 'text' }, // 可以根据需要添加更多列 ]; render() { return <SearchForm searchColumns={this.searchColumns} />; } } export default ParentComponent; ``` 这样,父组件就会将列名称和类型传递给搜索框组件,并自动生成相应的搜索框。每行最多显示三个搜索框,超过的搜索框会自动换行。你可以根据需要添加更多的列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值