React Native绑定this(bind(this))

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 (
      
        
          Welcome to React Native!
        
      
    );
  }
}

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.在调用函数的时候就绑定。


          Welcome to React Native!
        

4.在调用函数的时候写成箭头函数。

 this.callParent()}>
          Welcome to React Native!
        

如果需要传参数,则采用箭头函数的写法。

/**
 * 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 (
      
         this.callParent('father')}>
          Welcome to React Native!
        
         this.callParent('mother')}>
          Welcome to React Native!
        
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

AppRegistry.registerComponent('GlobalConstant', () => GlobalConstant);

你可能感兴趣的:(React Native绑定this(bind(this)))