[React日志]08-React中事件的写法总结

1:事件与原生事件类型 react中式on+首字母大写的事件名 例如onClick

如图 只需要on以后常用的事件都会提示出来
在这里插入图片描述

2:在Content.js中新建一系列的按钮来对事件进行学习

2.1 普通的函数绑定

  <button onClick={
    
    function(){
    
    alert('6666')}}>按钮1</button>

2.2 箭头函数的绑定

  <button onClick={
    
    ()=>{
    
    
     alert("7777");
  }}>按钮2</button> 

2.3 箭头函数带参数

 <button onClick={
    
    (e)=>{
    
    
   e.target.style.color="red";
  }}>按钮3</button>  

2.4

页面部分

   <button onClick={
    
    
	       this.show
	}>按钮4</button>

在render的上面定义一个函数 细节看alert中的提示

  constructor(props){
    
    
        super(props);
        this.state={
    
    
            num:10
        }
        //this.show9 = this.show9.bind(this);
    }
 
    show(){
    
    
            alert("按钮4被点击 但是里面this会脱离上下文关系");
            alert(this.state.num);//报错 this是undefined
    }

2.5 利用箭头函数 对this指向进行加强 this就是对象

  <button onClick={
    
    //show5是不能带参数
      this.show5
    }>按钮5</button>

函数的定义

 show5=()=>{
    
    
        alert(this.state.num);
    }

2.6 函数可以接收参数

<button onClick={
    
    //show6能带参数
                   ()=>{
    
    
                      this.show6("66666") 
                   }
                 }>按钮6</button>

函数的定义

 show6=(content)=>{
    
    
        alert(content);
    }

2.7 函数既能接收参数 也能返回触发的事件源

 <button onClick={
    
    //show7能带参数 还能带事件源
                   (e)=>{
    
    
                      this.show7("7777",e); 
                   }
                 }>按钮7</button>

函数的定义

 show7=(content,e)=>{
    
    
        e.target.innerHTML= content;
    }

2.8 利用bind加强this的指向

<button onClick={
    
    this.show8.bind(this)}>按钮8</button>
函数的定义

 show8(){
    
    
        alert(this.state.num);
    }

2.9 在state中利用bind加强指向 bind就是函数执行时候 this的指向

   <button onClick={this.show9} >按钮9</button>

函数的定义 show9里面的this就指向谁对象

 constructor(props){
    
    
        super(props);
        this.state={
    
    
            num:10
        }
        this.show9 = this.show9.bind(this);
    }
    show9(){
    
    
        alert(this.state.num);

猜你喜欢

转载自blog.csdn.net/u013034585/article/details/106535888
今日推荐