The article directories

    • preface
    • React bind option

preface

Bind (this) is often used in React or react-native click events. For example, a simple React-native click component:

export default class AwesomeProject extends Component {
  constructor(props){
    super(props);
    this.state = {
    }
  }

  handleClick () {
    console.log('this is:'.this);
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome} onPress={this.handleClick.bind(this)}> Welcome to React Native! </Text> </View> ); }}Copy the code

In the code above, we performed the click event functionbind(this)Operation if notbind(this)thethisWhat happens?



Bind (this), but bind(this) doesn’t. If there is no bind(this), this is the text component.

React bind option

Bind (this) = function(){}).bind(this) = function(){}). So we have four options:

  / / write 1
  <View onPress={this.handleClick.bind(this)}></View>

  / / write 2
  constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  / / writing 3
  <View onPress={()=>this.handleClick()}>

  / / write 4
  handleClick = () => {

  }
Copy the code

Since bind regenerates a new function, both render 2 and 3 generate a new function each time, so use 1 or 4 is recommended.