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来断点调试

  • 相关阅读:
    java中的socket编程有关printStream的println方法和write方法
    json在php中的用法
    js的数组处理函数splice
    将博客搬至CSDN
    mapreduce导出MSSQL的数据到HDFS
    基于信息熵的无字典分词算法
    搜索引擎手记(三)之网页的去重
    算法之常用的距离和相似度度量
    搜索引擎手记(二)之爬虫的开发
    搜索引擎手记(一)之引擎工作的开始
  • 原文地址:https://www.cnblogs.com/ariel-zhang/p/6812618.html
Copyright © 2011-2022 走看看