React之路-事件处理

191 阅读1分钟

react的事件处理

事件命名采用小驼峰命名 handleGetdata,而在使用 JSX 语法时你需要传入一个函数作为事件处理函数,而不是一个字符串

<button onClick={activateLasers}>
  Activate Lasers
</button>

阻止默认事件使用preventDefault(e.preventDefault()),而不能使用return false

在ES6 class 组件中,一般将事件处理函数添加到组件中作为一个方法使用

class Clock extends React.Component {
  constructor(props){
    super(props);
    this.state = {date:new Date()};

    //为了在回调函数中使用this,需要在构造函数中绑定this
    this.handleGetdata = this.handleGetdata.bind(this);
  }
  // 挂载
  componentDidMount() {
    this.timeId = setInterval(
      () =>this.getTime(),1000
    )
  }
  // 卸载
  componentWillUnmount() {
    clearInterval(this.timeId)
  }
  // 写法一
  handleGetdata(){
    // 使用this.setState更新数据
    // this.setState(state => ({
    //   isToggleOn: !state.isToggleOn
    // }));
  }
  // 写法二
  // public class fields 语法
  handleGetdata = () =>{

  }
  getTime() {
    this.setState({
      date: new Date()
    });
  }
  // 写法三
  render() {
    // 此语法确保 `handleClick` 内的 `this` 已被绑定。
    return (
          <button onClick={(如果需要参数,可以在传入e) => this.handleGetdata(参数)}>
        Click me
      </button>
    );
  }
  // render(){
  //   return(
  //     <div>
  //       <h2>当前时间 {this.state.date.toLocaleTimeString()}</h2>
  //     </div>
  //   )
  // }
}

向事件处理程序传递参数

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>