ES6+ 开发 React 组件
在这里简要的说一下这些语言新特性对 React 应用的开发有什么影响,这些 ES6+ 特性使得 React 开发更简单更有趣。
类
迄今为止,最能体现我们使用 ES6+ 来编写 React 组件的就是我们选择使用类定义语法。替代了使用 React.createClass 方法来定义一个组件,我们可以定义一个 bonafide ES6 类来扩展 React.Component:
|
1
2
3
4
5
|
class Photo extends React.Component { render() { return <img alt={this.props.caption} src={this.props.src} />; }} |
现在,你就会发现一个微妙的差异 —— 当使用定义类的时候语法更简洁:
|
1
2
3
4
5
|
// The ES5 wayvar Photo = React.createClass({ handleDoubleTap: function(e) { … }, render: function() { … },}); |
|
1
2
3
4
5
|
// The ES6+ wayclass Photo extends React.Component { handleDoubleTap(e) { … } render() { … }} |
值得关注的是,我们去掉了两个括号和一个分号,每个方法声明我们省略了一个冒号,一个关键字和一个分号。
当使用新的类定义时,所有的生命周期方法至少有一个是符合你期望的。类的 constructor 现在假设 role 之前是通过 componentWillMount 填充的:
|
1
2
3
4
|
// The ES5 wayvar EmbedModal = React.createClass({ componentWillMount: function() { … },}); |
|
1
2
3
4
5
6
7
|
// The ES6+ wayclass EmbedModal extends React.Component { constructor(props) { super(props); // Operations usually carried out in componentWillMount go here }} |
属性初始化程序
在 ES6+ 类的世界里,prop types 和 defaults live 在类自身作为静态属性。这些,在组件的初始化状态也是一样的,可以使用 ES7 property initializers 定义:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// The ES5 wayvar Video = React.createClass({ getDefaultProps: function() { return { autoPlay: false, maxLoops: 10, }; }, getInitialState: function() { return { loopsRemaining: this.props.maxLoops, }; }, propTypes: { autoPlay: React.PropTypes.bool.isRequired, maxLoops: React.PropTypes.number.isRequired, posterFrameSrc: React.PropTypes.string.isRequired, videoSrc: React.PropTypes.string.isRequired, },}); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// The ES6+ wayclass Video extends React.Component { static defaultProps = { autoPlay: false, maxLoops: 10, } static propTypes = { autoPlay: React.PropTypes.bool.isRequired, maxLoops: React.PropTypes.number.isRequired, posterFrameSrc: React.PropTypes.string.isRequired, videoSrc: React.PropTypes.string.isRequired, } state = { loopsRemaining: this.props.maxLoops, }} |
ES7 属性初始化程序操作内部类的 constructor,this 指向 construction 的类实例,所以初始化状态可以依赖于 this.props。值得关注的是,我们不再定义 prop 默认值和使用 getter 函数初始化状态对象。
Arrow 函数
React.createClass 方法用来在你的组件实例方法中执行一些额外的绑定工作,为了确保 this 关键字会指向组件实例:
|
1
2
3
4
5
6
7
|
// Autobinding, brought to you by React.createClassvar PostInfo = React.createClass({ handleOptionsButtonClick: function(e) { // Here, 'this' refers to the component instance. this.setState({showOptionsModal: true}); },}); |
自从我们不参与 React.createClass 方法,而是使用 ES6+ 类语法定义组件,看似需要手动绑定实例方法:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
// Manually bind, wherever you need toclass PostInfo extends React.Component { constructor(props) { super(props); // Manually bind this method to the component instance... this.handleOptionsButtonClick = this.handleOptionsButtonClick.bind(this); } handleOptionsButtonClick(e) { // ...to ensure that 'this' refers to the component instance here. this.setState({showOptionsModal: true}); }} |
幸运的是,通过绑定两个 ES6+ 特性 – arrow functions 和属性初始化程序 – 可以选择绑定组件实例:
|
1
2
3
4
5
|
class PostInfo extends React.Component { handleOptionsButtonClick = (e) => { this.setState({showOptionsModal: true}); }} |
ES6 的 arrow 函数体分享相同的词 this,用这来围绕他们的代码,这些可以达到我们预期的结果,也是 ES7 属性初始化程序在域内的方式。 Peek under the hood 来看看为什么能实现。
动态属性名称 & 模板字符串
其中一个对象常量增强是可以分配到一个派生属性名称。我们最初可能会像下面这样设置一些状态:
|
1
2
3
4
5
6
7
|
var Form = React.createClass({ onChange: function(inputName, e) { var stateToSet = {}; stateToSet[inputName + 'Value'] = e.target.value; this.setState(stateToSet); },}); |
现在,我们有能力构造通过一个运行时 JavaScript 表达式确定属性名称的对象。这里,我们使用了一个模板字符串来确定哪个属性设置状态:
|
1
2
3
4
5
6
7
|
class Form extends React.Component { onChange(inputName, e) { this.setState({ [`${inputName}Value`]: e.target.value, }); }} |
解构 & 传播属性
通常在编写组件的时候,我们可能想把大部分父组件的 props 传递给子组件,但不是所有。结合 ES6+ 解构和 JSX 传播属性,这个不需要多余的部分就能实现:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class AutoloadingPostsGrid extends React.Component { render() { var { className, ...others, // contains all properties of this.props except for className } = this.props; return ( <div className={className}> <PostsGrid {...others} /> <button onClick={this.handleLoadMoreClick}>Load more</button> </div> ); }} |
我们可以结合 JSX 传播属性和常规属性,利用一个简单的优先原则实现 overrides 和 defaults。这个元素会要求 className “override” 甚至是在 this.props 存在 className 属性:
|
1
2
3
|
<div {...this.props} className="override"> … </div> |
这个元素常规来说需要 className “base” ,除非 this.props 有 className 属性覆盖:
|
1
2
3
|
<div className="base" {...this.props}> … </div> |
希望大家能享受 ES6+ 语言特性给 React 开发带来的一些便利。
ES6+ 开发 React 组件的更多相关文章
- React组件开发入门
React 组件开发入门 Introduction 本文组成: Ryan Clark文章Getting started with React的翻译. 博主的实践心得. React由Facebook的程 ...
- 编写React组件的最佳实践
此文翻译自这里. 当我刚开始写React的时候,我看过很多写组件的方法.一百篇教程就有一百种写法.虽然React本身已经成熟了,但是如何使用它似乎还没有一个"正确"的方法.所以我( ...
- 从工程化角度讨论如何快速构建可靠React组件
前言 React 的开发也已经有2年时间了,先从QQ的家校群,转成做互动直播,主要是花样直播这一块.切换过来的时候,业务非常繁忙,接手过来的业务比较凌乱,也没有任何组件复用可言. 为了提高开发效率,去 ...
- react开发中如何使用require.ensure加载es6风格的组件
其实用的babel,在浏览器端就应该可以加载,之前少了个default: require.ensure([],(require) => { let A = require('./a.js').d ...
- webpack+react+redux+es6开发模式
一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...
- react复习总结(1)--react组件开发基础
这次是年后第一次发文章,也有很长一段时间没有写文章了.准备继续写.总结是必须的. 最近一直在业余时间学习和复习前端相关知识点,在一个公司呆久了,使用的技术不更新,未来真的没有什么前景,特别是我们这种以 ...
- sublime +react+es6开发环境
Babel Sublime3才有的插件,支持ES6.JSX语法高亮. 菜单->View->Syntax->Open all with current extension as...- ...
- React 组件开发注意事项
0.state的设定原则,如果render里用不到,则就不应该是一个state. 1.数组遍历时,用每一条数据的唯一标识作为key,尽量不要使用遍历的索引值作为key,如果它们从不重新排序,它们工作也 ...
- [webpack] 配置react+es6开发环境
写在前面 每次开新项目都要重新安装需要的包,简单记录一下. 以下仅包含最简单的功能: 编译react 编译es6 打包src中入口文件index.js至dist webpack配置react+es6开 ...
随机推荐
- django.template.exceptions.TemplateDoesNotExist: login.html 错误处理
登陆Login界面时候报错 Internal Server Error: /login/ Traceback (most recent call last): File , in inner resp ...
- QQ网页弹窗
QQ网页弹窗 1.网址:http://shang.qq.com/v3/index.html 2.选推广工具,提示语随便写 3.建一个html 网页,并把代码拷进去. 4.双击网页,就可以打开了.(用E ...
- web工程的路径问题详解
1.若/交由浏览器来解析,代表当前web站点的根路径:例:http://localhost:8080/ >超链接:<a href="/TestServlet ...
- redis 分布式读写锁
http://zhangtielei.com/posts/blog-redlock-reasoning.html 链接里这篇 blog 讨论了 redis 分布式锁的实现以及安全性 我要参考 基于单R ...
- jQuery基础与JavaScript与CSS交互-第五章
目录 JavaScript框架种类及其优缺点 jQuery库 jQuery对象$ 掌握基本选择器 掌握过滤选择器 掌握表单选择器 RIA技术 常见的RIA技术 Ajax Sliverlight Fle ...
- 在Shell脚本中获取指定进程的PID
注意这条命令用反引号(Tab上面的那个键)括起来,作用类似于${ } processId = ` ps -ef | grep fms.jar | grep -v grep | awk '{print ...
- iOS开发笔记(Swift)-针对Swift调用PPiFlatSegmentedControl项目的一些修改
PPiFlatSegmentedControl项目是一个很流行的开源iOS控件库,提供了扁平化风格(Flat style)的SegmentedControl,可以自定义segment的颜色,图标.大小 ...
- mysql之select语法
一:连接查询(外链接outer和内链接inner) 连接查询是另一种类型的多表查询.连接查询对多个表进行JOIN运算,简单地说,就是先确定一个主表作为结果集,然后,把其他表的行有选择性地“连接”在主表 ...
- iOS-常用的两个弹簧动画pop
POPSpringAnimation *popAna = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPosition]; popA ...
- 【LeetCode】21.合并两个有序链表
题目 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的. 示例: 输入:1->2->4, 1->3->4 输出:1->1-> ...