转自:https://blog.csdn.net/haoshidai/article/details/52244620
一 模块
1 引入模块以便使用
用import实现:
import '模块文件地址'
import 组件 from '模块文件地址'
2 导出模块
用export default实现:
export default class MyComponent extends Component{
...
}
引用:
import MyComponent from './MyComponent';
二 组件
1 定义组件
通过定义一个继承自React.Component的class来定义一个组件类:
class Photo extends React.Component {
render() {
...
}
}
2 定义组件方法
直接用名字(){},很像java定义类方法的写法:
class Photo extends React.Component {
componentWillMount() {
}
render() {
return (
<Image source={this.props.source} />
);
}
}
3 定义组件的属性类型和默认属性
统一使用static成员来实现:
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,
}; // 注意这里有分号
render() {
return (
<View />
);
} // 注意这里既没有分号也没有逗号
}
注意: 对React而言,static成员在IE10及之前版本不能被继承,而在IE11和其它浏览器上可以,有时会带来一些问题。React Native则不用担心这个问题。
4 初始化STATE
在构造函数中初始化(这样可以根据需要做一些计算):
class Video extends React.Component {
constructor(props){
super(props);
this.state = {
loopsRemaining: this.props.maxLoops,
};
}
}
5 把方法作为回调提供并使用
ES5下可以这么做:
//ES5
var PostInfo = React.createClass({
handleOptionsButtonClick: function(e) {
// Here, 'this' refers to the component instance.
this.setState({showOptionsModal: true});
},
render: function(){
return (
<TouchableHighlight onPress={this.handleOptionsButtonClick}>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
});
在ES5下,React.createClass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在认为这是不标准、不易理解的。
ES6下,需要通过bind来绑定this引用,或者使用箭头函数(它会绑定当前scope的this引用)来调用:
//ES6
class PostInfo extends React.Component
{
handleOptionsButtonClick(e){
this.setState({showOptionsModal: true});
}
render(){
return (
<TouchableHighlight
onPress={this.handleOptionsButtonClick.bind(this)}
onPress={e=>this.handleOptionsButtonClick(e)}
>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
}
箭头函数是在这里定义了一个临时的函数,箭头函数的箭头=>之前是一个空括号、单个的参数名、或用括号括起的多个参数名,而箭头之后可以是一个表达式(作为函数的返回值),或者是用花括号括起的函数体(需要自行通过return来返回值,否则返回的是undefined)。
即:箭头函数箭头前是参数,箭头后是函数体或返回值。
注意:
不论是bind还是箭头函数,每次被执行都返回的是一个新的函数引用,因此如果你还需要函数的引用去做一些别的事情(譬如卸载监听器),那么必须自己保存这个引用:
// 错误的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
}
onAppPaused(event){
}
}
// 正确的做法
class PauseMenu extends React.Component{
constructor(props){
super(props);
this._onAppPaused = this.onAppPaused.bind(this);//注意这里
}
componentWillMount(){
AppStateIOS.addEventListener('change', this._onAppPaused); //还有这里
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this._onAppPaused);
}
onAppPaused(event){
}
}
三 Mixins
ES5下,经常使用mixin来为类添加一些新的方法,如PureRenderMixin:
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],
render: function() {
return <div className={this.props.className}>foo</div>;
}
});
但React官方已经不再打算在ES6里继续推行Mixin,官方推荐,对于库编写者而言,应尽快放弃Mixin的编写方式,推荐一种新的编码方式:
//Enhance.js
import { Component } from "React";
export var Enhance = ComposedComponent => class extends Component {
constructor() {
this.state = { data: null };
}
componentDidMount() {
this.setState({ data: 'Hello' });
}
render() {
return <ComposedComponent {...this.props} data={this.state.data} />;
}
};
//HigherOrderComponent.js
import { Enhance } from "./Enhance";
class MyComponent {
render() {
if (!this.data) return <div>Waiting...</div>;
return <div>{this.data}</div>;
}
}
export default Enhance(MyComponent); // Enhanced component
用一个“增强函数”,来为某个类增加一些方法,并且返回一个新类,这无疑能实现mixin所实现的大部分需求。
四 解构与属性延展
结合使用ES6+的解构和属性延展,在给子组件传递一批属性更为方便了。下面的例子把className以外的所有属性传递给div标签:
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>
);
}
}
下面这种写法,则是传递所有属性的同时,用新的className值进行覆盖({…this.props}写在前边):
<div {...this.props} className="override">
…
</div>
这个例子则相反,如果属性中没有包含className,则提供默认的值,而如果属性中已经包含了,则使用属性中的值({…this.props}写在后边)
<div className="base" {...this.props}>
…
</div>
更多ES6的细节可以参考阮一峰前辈的《ECMAScript 6入门》:
http://es6.ruanyifeng.com/
ES6是大势所趋,建议大家日常使用js的时候逐渐的转到ES6上,适应ES6的新特性,这样才不会落伍哈。
====================================================================================================================================下面是我自己转载后的补充========================================
一、部分转自:https://blog.csdn.net/future_challenger/article/details/52518500
React与ES6系列:
1. React与ES6(一)开篇介绍
2. React和ES6(二)ES6的类和ES7的property initializer
3. React与ES6(三)ES6类和方法绑定
4. React与ES6(四)ES6如何处理React mixins
ES2015(也就是ES6)带来了很多新的语言特性。比如:类、箭头方法、rest参数、promise、generator等很多。如果你对ES6还不是很熟悉的话可以看这里。
但是浏览器对于ES6的支持还不是很好。你可以看看这个ES6兼容表。显而易见的是不同浏览器对于ES6的兼容参差不齐。于是就有人想把ES6的代码转成ES5的不就可以兼容了吗。
这其中做的最好的就是Babel, 一个非常棒的工具。后面会详细的介绍如何使用。
准备开发环境
为了可以正常开发,那么就需要用到webpack。这个工具可以把模块和相关的依赖项都打包到一起。之后,只要在浏览器中引用打包的脚本。
1、首先你需要安装nodejs。如果你还没有安装的话,直接去官网下载最新的安装包安装即可。
2、接下来安装webpack。npm install webpack --save-dev。
3、安装babel-loader。npm install babel-loader babel-preset-es2015 babel-preset-react --save。有了babel-loader和对应的preset,就可以把ES6的代码转换为ES5了。但是,之前还需要配置babel-loader。
4、安装react以及相关包。npm install react react-dom --save。
import React from 'react'; // 1
// 2
export default class HelloWorld extends React.Component {
// 3
render() {
// 4
return <h1>Hello from {this.props.phrase}</h1>
}
}
解析:
1. 把React库import引入到React变量中。
2. 定义了一个我们自己的组件HelloWorld,这个组件继承(extends)自React.Component。注意:在类的前面还有关键字export default,在别的模块中import并使用HelloWorld组件。
3. 覆盖React组件的render方法。
4. render方法返回JSX定义的html元素,这个元素内部显示的文本通过解析this.props.phrase获得。
二、疑问:
每次用dva创建项目时,会在nodejs的node_module中的dva-cli里面create很多东西吗?是不是建议每创建个项目,把dva单独安装到项目里啊?方便删除?
初识 Dva链接:https://juejin.im/entry/5852184b128fe1006b5454c6
http://cnodejs.org/topic/5895a8541555834405dde673
https://github.com/dvajs/dva-docs/blob/master/v1/zh-cn/getting-started.md
https://yq.aliyun.com/articles/269127
dva 入门:手把手教你用写应用:
https://juejin.im/entry/5879a63c1b69e600582da314#comment
https://juejin.im/entry/5879a63c1b69e600582da314