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 (
      <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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容