es5的data语法_React Native之ES5/ES6语法差异对照表 | 六阿哥博客

// 在ES5下,React.createClass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在逐步认为这反而是不标准、不易理解的。

var PostInfo = React.createClass({

handleOptionsButtonClick: function(e) {

// Here, 'this' refers to the component instance.

this.setState({showOptionsModal: true});

},

render: function(){

return (

{this.props.label}

)

},

});

// 在ES6下,你需要通过bind来绑定this引用,或者使用箭头函数(它会绑定当前scope的this引用)来调用

class PostInfo extends React.Component

{

handleOptionsButtonClick(e){

this.setState({showOptionsModal: true});

}

render(){

return (

onPress={this.handleOptionsButtonClick.bind(this)}

onPress={e=>this.handleOptionsButtonClick(e)}

>

{this.props.label}

)

},

}

// 箭头函数实际上是在这里定义了一个临时的函数,箭头函数的箭头=>之前是一个空括号、单个的参数名、或用括号括起的多个参数名,而箭头之后可以是一个表达式(作为函数的返回值),或者是用花括号括起的函数体(需要自行通过return来返回值,否则返回的是undefined)。

()=>1

v=>v+1

(a,b)=>a+b

()=>{

alert("foo");

}

e=>{

if (e == 0){

return 0;

}

return 1000/e;

}

// 需要注意的是,不论是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){

}

}

// 从这个帖子中我们还学习到一种新的做法

// 正确的做法

class PauseMenu extends React.Component{

componentWillMount(){

AppStateIOS.addEventListener('change', this.onAppPaused);

}

componentDidUnmount(){

AppStateIOS.removeEventListener('change', this.onAppPaused);

}

onAppPaused = (event) => {

// 把方法直接作为一个arrow function的属性来定义,初始化的时候就绑定好了this指针

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值