react修正指针的3种方法及传参的2种方式

修正指针的3种方法

1.在构造器constructor中修正指针

优势:只执行一次
eg:

 constructor(props) {
       super(props);
       this.Enter = this.Enter.bind(this);
  }
import React,{Component} from 'react';  //导入必要的库和组件
class App extends Component {
  constructor() {
    super();  //ES6继承以后,必须在第一句调用父类构造器super()
    this.sayHi = this.sayHi.bind(this);
  }
  sayHi() {
    alert("hi");
    console.log(this);
  }
  render() {
    var arr = ["qq","q7","wey5"];
    return(
        

hello world

    { arr.map(function(item,index){ return
  • {item}
  • }) }
) } } export default App;

2.使用bind绑定

 

3.利用箭头函数绑定

 
this.Enter(event)}>

传参的两种方式

1.onClick={()=>this.方法(参数)}

import React,{Component} from 'react';  //导入必要的库和组件
class App extends Component {
  constructor() {
    super();  //ES6继承以后,必须在第一句调用父类构造器super()
    this.sayHi = this.sayHi.bind(this);
  }
  sayHi(username) {
    alert("hi" + username);
    console.log(this);
  }
  render() {
    var arr = ["qq","q7","wey5"];
    return(
        

hello world

    { arr.map(function(item,index){ return
  • {item}
  • }) }
) } } export default App;

2.onClick={this.方法.bind(this, 参数)}

import React,{Component} from 'react';  //导入必要的库和组件
class App extends Component {
  constructor() {
    super();  //ES6继承以后,必须在第一句调用父类构造器super()
    this.sayHi = this.sayHi.bind(this);
  }
  sayHi(username) {
    alert("hi" + username);
    console.log(this);
  }
  render() {
    var arr = ["qq","q7","wey5"];
    return(
        

hello world

    { arr.map(function(item,index){ return
  • {item}
  • }) }
) } } export default App;

你可能感兴趣的:(react修正指针的3种方法及传参的2种方式)