ReactNative-从0到上线Appstore(2) 箭头函数

来源:互联网 发布:苹果手机淘宝p图软件 编辑:程序博客网 时间:2024/06/06 12:43

现在开始说RN中的this 以及箭头函数,它其实是ES6中的特性。

先看一段代码

_getSegment(){    return (<Segment      viewidth={180}      datas={['任务','咨询']}      borderColor={Base.commonGreenColor}      selectItem={index => this._tapSegment(index)}      />)  }<NavHeader          nav={this.props.nav}          title={"任务"}          //第一种情况          middleView={this._getSegment.bind(this)}          //第二种情况          middleView={() => this._getSegment()}          //第三种情况          middleView={() => {            return (<Segment                      viewidth={180}                      datas={['任务','咨询']}                      borderColor={Base.commonGreenColor}                      selectItem={index =>                       this._tapSegment(index)}                      />)                  }}          />

第一种情况是基本写法,在js中this._getSegment是指_getSegment指针地址,方法也是一种数据类型,有自己的属性等,this._getSegment()是调用这个方法。
而middleView需要传一个方法不是调用方法,那么就应该middleView={this._getSegment},这么写也是对的,但是如果在_getSegment方法中用到this,那么会报错,this是undefined,因为作用域。所以就得绑定这个this传过去,即bind(this).

下面两种都是箭头函数的写法,他是匿名函数,是拥有词法作用域的this,内部不会产生自己的this也就是说this是本身所在作用域中的this。
有些特性可以参考下面文章

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arrow_functions

http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001438565969057627e5435793645b7acaee3b6869d1374000

0 0
原创粉丝点击