ES5语法React.createClass会自动绑定this,ES6的写法,不再自动绑定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:'语文',
},
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);
此时如果不绑定,在函数中用到了this,必然会报错。
解决办法有两个:
1.在constructor中进行函数绑定。
this.callParent = this.callParent.bind(this);
2.将自定义的函数写成箭头函数形式
callParent = () =>{
alert(this.state.parent.name);
}
3.在调用函数的时候就绑定。
<Text style={styles.welcome}onPress={this.callParent.bind(this)}>
Welcome to React Native!
</Text>
4.在调用函数的时候写成箭头函数。
<Text style={styles.welcome} onPress={ ()=> this.callParent()}>
Welcome to React Native!
</Text>
如果需要传参数,则采用箭头函数的写法。
/**
* 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:'语文',
},
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);