React 之事件处理

2019-03-28  本文已影响0人  甘道夫老矣

一,认识React 事件中写法为

import React, { Component } from 'react'
class ChildrenTwo extends Component {
handleClick=(e)=>{
    e.preventDefault();
    console.log('链接被点击');
}
    render () {
        return (
        <div>
          <button onClick={activateLasers}>
          激活按钮
        </button>
            <h1>子组件2</h1>
          //如果你需要用a标记的话肯定会有个默认跳转,
         <a href="#" onClick={handleClick}>
          激活按钮
          </button
         </a>
        )
    }
}
export default ChildrenTwo

注意:你必须谨慎对待 JSX 回调函数中的 this,
这里有两种方式可以解决。如果你正在使用实验性的属性初始化器语法,你可以使用属性初始化器来正确的绑定回调函数:

(感觉这种方法好用一点点,es6的箭头函数,也是推荐的用法)
class Button extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () => {
    console.log('this is:', this);
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

如果你没有使用属性初始化器语法,你可以在回调函数中使用 箭头函数:

class Button extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中,一般传参的话用这个,
    //      但是要防止加载时候就调用这个方法的问题
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

还有一种写法:


class Poker extends React.Component {
  constructor(props) {
    super(props);
    this.state = { suit: 1 };
    this.handleHeart = this.handleHeart.bind(this);
  
  }
  handleHeart() {
    this.setState({ suit: (this.state.suit+1) });
  }
 render() {
            return <div onClick={this.onClickList}>点我点我点我</div>
  }
}

二,向事件中传递参数

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
两种方式是等价的。

--参数 e 作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind 的方式,事件对象以及更多的参数将会被隐式的进行传递。
需要通过 bind 方法来绑定参数,第一个参数指向 this,第二个参数开始才是事件函数接收到的参数:

<button onClick={this.handleClick.bind(this, props0, props1, ...}></button>

handleClick(porps0, props1, ..., event) {
    // your code here
}
//事件:this.handleclick.bind(this,要传的参数)
//函数:handleclick(传过来的参数,event)

三.点击修改参数,赋值

class Home extends Component {
    constructor(props,context) {
        super(props,context)
        this.state = {
            clickbtn:"指标监测"
        }
    }
////错误
//this.state.clickbtn='React';
//但是异步的我不知道是不是这样写了;
//正确
    handle=(val)=>{
        this.setState({
            clickbtn:val.name
        })
    }
}
上一篇 下一篇

猜你喜欢

热点阅读