ES5語(yǔ)法React.createClass會(huì)自動(dòng)綁定this,ES6的寫法,不再自動(dòng)綁定this。
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class GlobalConstant extends Component {
constructor(props){
super(props);
this.state = {
zuoye:{
book:'語(yǔ)文',
},
parent:{
name:'xxx',
phone:'11111111',
},
}
}
callParent(){
alert(this.state.parent.name);
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome} onPress={this.callParent}>
Welcome to React Native!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('GlobalConstant', () => GlobalConstant);
此時(shí)如果不綁定嗤放,在函數(shù)中用到了this,必然會(huì)報(bào)錯(cuò)。
解決辦法有兩個(gè):
1.在constructor中進(jìn)行函數(shù)綁定。
this.callParent = this.callParent.bind(this);
2.將自定義的函數(shù)寫成箭頭函數(shù)形式
callParent = () =>{
alert(this.state.parent.name);
}
3.在調(diào)用函數(shù)的時(shí)候就綁定。
<Text style={styles.welcome}onPress={this.callParent.bind(this)}>
Welcome to React Native!
</Text>
4.在調(diào)用函數(shù)的時(shí)候?qū)懗杉^函數(shù)找爱。
<Text style={styles.welcome} onPress={ ()=> this.callParent()}>
Welcome to React Native!
</Text>
如果需要傳參數(shù),則采用箭頭函數(shù)的寫法泡孩。
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class GlobalConstant extends Component {
constructor(props){
super(props);
this.state = {
zuoye:{
book:'語(yǔ)文',
},
father:{
name:'xxx',
phone:'11111111',
},
mother:{
name:'xxx',
phone:'00000000',
},
}
this.callParent = this.callParent.bind(this);
}
callParent = (parent) => {
alert(this.state[parent].phone);
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome} onPress={ ()=> this.callParent('father')}>
Welcome to React Native!
</Text>
<Text style={styles.welcome} onPress={ ()=> this.callParent('mother')}>
Welcome to React Native!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('GlobalConstant', () => GlobalConstant);