美文网首页
React.js中常用的ES6写法总结

React.js中常用的ES6写法总结

作者: 天空之城_2692 | 来源:发表于2018-12-29 19:06 被阅读12次

React.js中常用的ES6写法总结 - CSDN博客

一 模块

1 引入模块以便使用

用import实现:

1、import '模块文件地址'

2、import 组件 from '模块文件地址'

2 导出模块

用export default实现:

exportdefaultclassMyComponent extends Component{    ...}

引用:

import MyComponent from'./MyComponent';

二 组件

1 定义组件

通过定义一个继承自React.Component的class来定义一个组件类:

class Photo extends React.Component {   

 render() {      ...    }

}

2 定义组件方法

直接用名字(){},很像java定义类方法的写法:

classPhoto 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下这么做

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}></TouchableHighlight>

<Text>  {this.props.label}</Text>

)   

 },

});

//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还是箭头函数,每次被执行都返回的是一个新的函数引用,因此如果你还需要函数的引用去做一些别的事情(譬如卸载监听器),那么必须自己保存这个引用:

三 Mixins

ES5下,经常使用mixin来为类添加一些新的方法,如PureRenderMixin:

用一个“增强函数”,来为某个类增加一些方法,并且返回一个新类,这无疑能实现mixin所实现的大部分需求

四 解构与属性延展

结合使用ES6+的解构和属性延展,在给子组件传递一批属性更为方便了。下面的例子把className以外的所有属性传递给div标签:

...other表示数组,this.props第一个值给classname,剩余的给...others

下面这种写法,则是传递所有属性的同时,用新的className值进行覆盖({…this.props}写在前边)

这个例子则相反,如果属性中没有包含className,则提供默认的值,而如果属性中已经包含了,则使用属性中的值({…this.props}写在后边)

相关文章

网友评论

      本文标题:React.js中常用的ES6写法总结

      本文链接:https://www.haomeiwen.com/subject/bmcbkftx.html