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 way var Photo = React.createClass({ handleDoubleTap: function (e) { … }, render: function () { … }, }); |
1
2
3
4
5
|
// The ES6+ way class Photo extends React.Component { handleDoubleTap(e) { … } render() { … } } |
值得关注的是,我们去掉了两个括号和一个分号,每个方法声明我们省略了一个冒号,一个关键字和一个分号。
当使用新的类定义时,所有的生命周期方法至少有一个是符合你期望的。类的 constructor 现在假设 role 之前是通过 componentWillMount 填充的:
1
2
3
4
|
// The ES5 way var EmbedModal = React.createClass({ componentWillMount: function () { … }, }); |
1
2
3
4
5
6
7
|
// The ES6+ way class 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 way var 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+ way class 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.createClass var 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 to class 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开 ...
随机推荐
- # 2019-2020-3 《Java 程序设计》实验一:Java开发环境的熟悉
2019-2020-3 <Java 程序设计>实验一:Java开发环境的熟悉-------1 一.实验要求: 1 建立"自己学号exp1"的目录 2 在"自己 ...
- instr()函数--支持模糊查询
1)instr()函数的格式 (俗称:字符查找函数) 格式一:instr( string1, string2 ) / instr(源字符串, 目标字符串) 格式二:instr( strin ...
- Alpha冲刺 - (5/10)
Part.1 开篇 队名:彳艮彳亍团队 组长博客:戳我进入 作业博客:班级博客本次作业的链接 Part.2 成员汇报 过去两天完成了哪些任务 基于ssm框架的前后端交互测试,结合微信小程序demo 展 ...
- Hive记录-Beeline常用操作命令
Beeline和其他工具有一些不同,执行查询都是正常的SQL输入,但是如果是一些管理的命令, 比如进行连接,中断,退出,执行Beeline命令需要带上"!",不需要终止符.常用命令 ...
- uniGUI经验几则
uniGUI经验几则 (2015-11-07 21:42:41) 转载▼ 标签: it 分类: uniGUI 1.uniTimer的妙用 很多时候,都会遇到在一个uniForm或者uniFrame加载 ...
- FFmpeg原始帧处理-滤镜API用法详解
本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10429145.html 在FFmpeg中,滤镜(filter)处理的是未压缩的原始音视频 ...
- confluence与jira账号对接、查看到期时间及问题总结
前面介绍了对于confluence和jira的破解版安装记录,下面简单记录下confluence和jira结合配置:安装顺序:先安装Jira,然后安装Confluence,在Confluence安装过 ...
- Go语言运算符
目录 算术运算符 注意事项 赋值运算符 逻辑运算符 短路与和短路或 关系运算符 位运算符 其他运算符 运算符优先级 运算符用于在程序运行时执行数学或逻辑运算. Go 语言内置的运算符有:算术运算符.赋 ...
- JavaScript在IE和Firefox的不兼容问题解决方法总结
1.兼容Firefox的 outerHTML,Firefox中没有outerHtml的方法. if (window.HTMLElement) { HTMLElement.prototype.__def ...
- [CocoaPods]常见问题
“现在Swift有一个内置的包管理器,CocoaPods会停止开发吗?” Swift Package Manager(SPM)处于“早期设计和开发”阶段[1].它目前不支持iOS,观看操作系统或Obj ...