React(5) --绑定函数事件

绑定函数事件react

在以类继承的方式定义的组件中,为了能方便地调用当前组件的其余成员方法或属性(如:this.state),一般须要将事件处理函数运行时的 this 指向当前组件实例。dom

run(){
    alert('我是一个run方法')
}函数

<button onClick={this.run}>执行方法</button>  this

//方法不须要加(),加了(),一旦页面加载进来就执行了 spa

绑定事件处理函数this的几种方法:code

方法1:blog

run(){
     alert(this.state.name)
}
<button onClick={this.run.bind(this)}>按钮</button>  //不绑定this的话,上面的方法里面的this就指向不了,拿不到数据

方法2:继承

constructor(props){
        super(props);   //固定写法
        this.state={
            name:'我是一个home组件' 
        }   
        //构造函数中改变
        this.run = this.run.bind(this);
  }

run(){
        alert(this.state.name)
}
<button onClick={this.run}>按钮</button>

方法3:事件

//直接使用箭头函数 
run=()=> { alert(this.state.name) } <button onClick={this.run}>按钮</button>

函数方法里传值,改变state的值get

setName=(str)=>{
      //改变state的值
      this.setState({
          username:str
      })
}
<button onClick={this.setName.bind(this,'张三')}>执行方法传值</button>

<button onClick={this.setName.bind(this,'张三','李四')}>执行方法传值</button> 

 获取dom节点方法

方法1:

run=(event)=> {
        //alert(event.target)  //获取执行事件的dom节点
//alert(event.target.getAttribute('aid')) //获取dom的属性
event.target.style.background='red'; }
<button aid="123" onClick={this.run}>按钮</button>

 方法2:

import React from 'react';

class List extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            username:''
         };
    }
    inputChange=()=>{
        /*
            获取dom节点
                一、给元素定义ref属性
                    <input ref="username" />
                二、经过this.refs.username 获取dom节点
        
        */
        let val=this.refs.username.value;
        this.setState({
            username:val
        })
    }
    getInput=()=>{
        alert(this.state.username);
    }
    //键盘事件
    inputKeyUp=(e)=>{
        console.log(e.keyCode);
        if(e.keyCode==13){
            alert(e.target.value);
        }
    }
    inputonKeyDown=(e)=>{
        console.log(e.keyCode);
        if(e.keyCode==13){
            alert(e.target.value);
        }
    }
    render() {
        return (
            <div>  
                  {/* 获取表单的值

                一、监听表单的改变事件                        onChange
                二、在改变的事件里面获取表单输入的值            ref获取 
                三、把表单输入的值赋值给username              this.setState({})
                四、点击按钮的时候获取 state里面的username     this.state.username
                 */}
                <input ref="username" onChange={this.inputChange}/> <button onClick={this.getInput}>获取input的值</button>
                <br /><br /> <hr />  
                <h2>键盘事件</h2>
                <input onKeyUp={this.inputKeyUp}/>
                <br /><br />
                <input onKeyDown={this.inputonKeyDown}/>
            </div>
        );
    }
}

export default List;
相关文章
相关标签/搜索