zoukankan      html  css  js  c++  java
  • react绑定事件的几种写法

    方法一:最麻烦的写法,不推荐

    import React from 'react';
    class App extends React.Component {
      handleClick() {
        alert('点击')
      }
      render() {
        return (
          <div>
            <button onClick={this.handleClick.bind(this)}>click</button>
          </div>
        )
      }
    }
    export default App;

    方法二:在构造函数里统一绑定,不常用。

    import React from 'react';
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this)
      }
      handleClick() {
        alert('点击')
      }
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>click</button>
          </div>
        )
      }
    }
    export default App;

    方法三:最常见的写法。

    import React from 'react';
    class App extends React.Component {
      constructor(props) {
        super(props);
      }
      handleClick = () => {
        alert('点击')
      }
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>click</button>
          </div>
        )
      }
    }
    export default App;

    方法四:可以传参数。

    import React from 'react';
    class App extends React.Component {
      constructor(props) {
        super(props);
      }
      handleClick (e) {
        alert(e)
      }
      render() {
        return (
          <div>
            <button onClick={(e) => this.handleClick(e)}>click</button>
          </div>
        )
      }
    }
    export default App;
  • 相关阅读:
    P4149 [IOI2011]Race dsu on tree
    CodeForces
    2020牛客国庆集训派对day2 CHEAP DELIVERIES
    Hero In Maze
    topo排序
    今年暑假不AC
    小国的游戏
    Stall Reservations
    博弈论
    Reversed Words
  • 原文地址:https://www.cnblogs.com/superlizhao/p/11010746.html
Copyright © 2011-2022 走看看