美文网首页React
react 事件绑定、获取this、event、点击时参数

react 事件绑定、获取this、event、点击时参数

作者: 暴躁程序员 | 来源:发表于2022-04-05 08:17 被阅读0次
  1. 以下四种方式都可以传递 this 和 event 参数
  2. 在jsx中调用函数用this.函数名,不可直接使用this.函数名()

1. this.functionName.bind(this,args) ------ bind方式

  1. 在this之后传递点击时参数
  2. 默认最后一个参数是event参数
import React from "react";
class Component1 extends React.Component {
  fn1Bind(param, e) {
    console.log(this);
    console.log(param);
    console.log(e);
    console.log(this.props.arg1);
  }
  render() {
    return (
      <div>
        <button onClick={this.fn1Bind.bind(this, "other params")}>
          bind 绑定
        </button>
      </div>
    );
  }
}

function App() {
  return (
    <div>
      <Component1 arg1="arg1" />
    </div>
  );
}

export default App;

2.(e) => {this.functionName(args, e)} --- 箭头函数中调函数方式

  1. 在箭头函数的形参中获取event参数,并传递给函数
  2. 可传递点击时参数
import React from "react";
class Component1 extends React.Component {
  fnJianTou(param, e) {
    console.log(this);
    console.log(param);
    console.log(e);
    console.log(this.props.arg1);
  }
  render() {
    return (
      <div>
        <button
          onClick={(e) => {
            const param = "other param";
            this.fnJianTou(param, e);
          }}
        >
          箭头函数的方式
        </button>
      </div>
    );
  }
}

function App() {
  return (
    <div>
      <Component1 arg1="arg1" />
    </div>
  );
}

export default App;

3.匿名函数方式

无法传递点击时参数

import React from "react";
class Component1 extends React.Component {
  fn2Function = (e) => {
    console.log(this);
    console.log(e);
    console.log(this.props.arg1);
  };
  render() {
    return (
      <div>
        <button onClick={this.fn2Function}>匿名函数</button>
      </div>
    );
  }
}

function App() {
  return (
    <div>
      <Component1 arg1="arg1" />
    </div>
  );
}

export default App;

4. 构造函数 constructor 中引用 bind 方式

无法传递点击时参数

import React from "react";
class Component1 extends React.Component {
  constructor(props) {
    super(props);
    this.fn3Constructor = this.fn3Constructor.bind(this);
  }
  fn3Constructor(e) {
    console.log(this);
    console.log(e);
    console.log(this.props.arg1);
  }
  render() {
    return (
      <div>
        <button onClick={this.fn3Constructor}>构造函数中引用 bind</button>
      </div>
    );
  }
}

function App() {
  return (
    <div>
      <Component1 arg1="arg1" />
    </div>
  );
}

export default App;

相关文章

网友评论

    本文标题:react 事件绑定、获取this、event、点击时参数

    本文链接:https://www.haomeiwen.com/subject/nlqxsrtx.html