zl程序教程

您现在的位置是:首页 >  其它

当前栏目

事件处理--函数的调用(含this关键字的)

函数 -- 调用 关键字 this 事件处理
2023-09-27 14:25:18 时间

事件处理一: 触发函数的方法

import React from 'react'


export default class App extends React.Component {
    render() {
        return (
            <div>
                <input/>
                <button onClick={
                    ()=>{
                        alert("触发函数")
                    }
                }>add 匿名函数触发</button>

                <input/>
                <button onClick={this.handleClick}>add 单独函数触发</button>

                <button onClick={this.handleClick2}>add 单独函数触发,函数另外一种写法</button>

                <button onClick={ ()=>{
                    this.handleClick()
                    this.handleClick2()
                }}>add 里面可以指定执行多个函数</button>
            </div>
        )
    }

    handleClick(){
        console.log("函数触发1")
    }
    handleClick2=() =>{
        console.log("函数触发2")
    }

}

 https://www.bilibili.com/video/BV1dP4y1c7qd/?p=10&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

 

事件二: 含this关键字的 函数调用方法

import React from 'react'


export default class App extends React.Component {

    a="变量a"

    render() {
        return (
            <div>
                {/* 直接匿名函数可以获取类的变量 */}
                  <button onClick={
                    ()=>{
                        console.log(this.a)   
                    }
                }>add 匿名函数触发</button>
                
                {/* 函数调用,函数里面要拿类里面的变量
                要加bind 改变this的指向为类 
                如果加call 改变他会自动执行一次指定的函数,但是点击是不会触发成功的
                */}
                <button onClick={this.handleClick.bind(this)}>add 单独函数触发</button>
                <button onClick={this.handleClick2}>add 调用匿名函数触发--(推荐写法)</button>

                {/* 单个调用写法 */}
                <button onClick={  ()=>this.handleClick3()}>add 匿名函数里面调用函数触发 --非常推荐的写法-方便传参</button>
                {/* 调用多个函数写法 */}
                <button onClick={  ()=>{
                       this.handleClick3()
                       this.handleClick3()
                    }}>add 匿名函数里面调用函数触发</button>
            </div>
        )
    }

    // 调用的时候要加bind指定this
    handleClick(){
        console.log("函数触发1",this.a)
    }

     // 调用的时候 这种匿名 函数 不需要指定this
     handleClick2=()=>{
        console.log("匿名函数触发",this.a)
    }
    handleClick3(){
        console.log("匿名函数触发",this.a)
    }


}

 

this看谁去调用,匿名函数指向是类的本身