zoukankan      html  css  js  c++  java
  • React事件处理程序

    function ActionLink() {
      function handleClick(e) {
        e.preventDefault();
        console.log('The link was clicked.');
      }
    
      return (
        <a href="#" onClick={handleClick}>
          Click me
        </a>
      );
    }

    When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

    Becareful about 'this':

    class Toggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {isToggleOn: true};
    
        // This binding is necessary to make `this` work in the callback
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState(prevState => ({
          isToggleOn: !prevState.isToggleOn
        }));
      }
    
      render() {
        return (
          <button onClick={this.handleClick}>
            {this.state.isToggleOn ? 'ON' : 'OFF'}
          </button>
        );
      }
    }
    
    ReactDOM.render(
      <Toggle />,
      document.getElementById('root')
    );

    或者可以用下面的方法解决: (利用ES6箭头函数)

    class LoggingButton extends React.Component {
      // This syntax ensures `this` is bound within handleClick.
      // Warning: this is *experimental* syntax.
      handleClick = () => {
        console.log('this is:', this);
      }
    
      render() {
        return (
          <button onClick={this.handleClick}>
            Click me
          </button>
        );
      }
    }

    或者

    class LoggingButton extends React.Component {
      handleClick() {
        console.log('this is:', this);
      }
    
      render() {
        // This syntax ensures `this` is bound within handleClick
        return (
          <button onClick={(e) => this.handleClick(e)}>
            Click me
          </button>
        );
      }
    }

     以上均来自于react官网docs。

    可以在js 中用debugger来断点调试

  • 相关阅读:
    使用Intent传递类对象
    C#中关于类的序列化
    Android 中使用内存监测工具Heap,及内存分析工具 MAT
    Android Framework 记录之一
    Android 2.3发短信详细流程
    AIDL原理解析
    eclipse 快捷键
    什么时候加上android.intent.category.DEFAULT和LAUNCHER
    Monkey测试简介
    Phone状态的监听机制
  • 原文地址:https://www.cnblogs.com/ariel-zhang/p/6812618.html
Copyright © 2011-2022 走看看