react事件绑定的四种方式及ref

文章介绍了在React组件中处理事件时,四种不同的this绑定方法:直接在事件处理函数内使用,使用bind方法,使用箭头函数,以及通过调用方法。每种方法都有其特点,例如bind用于确保this正确指向,箭头函数则能直接保留上下文的this。同时,文章还提及了使用ref获取DOM元素的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:

<button onClick={()=>{console.log(this.text)}}>方式一</button>

直接写在内部,不会导致this丢失,但是代码不够直观


方式二:

<button onClick={this.click2.bind(this,"传了一个参数")}>方式二</button>

click2(param){
    console.log(this.text)
    console.log(param)
}

//您也可以在构造中绑定
  constructor(props) {
    super(props);
    this.click2 = this.click2.bind(this);
  }

this会发生改变,因此需要使用bind()来更正this指向,同样的还有call()、apply()方法,call()、apply()方法会自动执行触发,bind为手动选择触发


 方式三:

<button onClick={this.click3}>方式三</button>

  click3=()=>{
    console.log(this.text)
  }

箭头函数可以直接引用this,注意若是在this.click3后面加个()的话则会自动触发点击事件


方式四:

<button onClick={()=>this.click4()}>方式四</button>

  click4=()=>{
    console.log(this.text)
  }

可以直接引用this,可以进行传参 


import ReactDOM from 'react-dom/client';
import React, { Component } from 'react'


export default class Ikun extends Component {

  text="爱坤"

  render() {
    return (
      <div>
        <input></input>
        <button onClick={()=>{console.log(this.text)}}>方式一</button>
        <button onClick={this.click2.bind(this,"传了一个参数")}>方式二</button>
        <button onClick={this.click3}>方式三</button>
        <button onClick={()=>this.click4()}>方式四</button>
      </div>
    )
  }

  click2(param){
    console.log(this.text)
    console.log(param)
  }
  click3=()=>{
    console.log(this.text)
  }
  click4=()=>{
    console.log(this.text)
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Ikun />
);

  • ref用于获取指定节点元素,使用示例如下
import ReactDOM from 'react-dom/client';
import React, { Component } from 'react'


export default class Ikun extends Component {

    constructor(props) {
        super(props);
        this.click = this.click.bind(this);
        this.inputDom=React.createRef();
    }

    render() {
        return (
            <div>
                <input ref={this.inputDom}></input>
                <button onClick={() => this.click()}>点击</button>
            </div>
        )
    }

    click=()=>{
        console.log(this.inputDom.current.value)
    }

}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Ikun />
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值