React - 事件处理

相似于DOM事件处理,有几点不一样之处:html

  • React的事件名字是首字母小写的驼峰式写法,而不是小写的。
  • 在JSX里面,事件处理器是一个函数,而不是一个字符串。

例子,HTML:react

<button onclick="activateLasers()">
  Activate Lasers
</button>

React:git

<button onClick={activateLasers}>
  Activate Lasers
</button>
  • 在React里面,不能经过返回false来阻止事件的默认行为,必须调用preventDefault函数。

例子,HTML:github

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

React:函数

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

使用React不须要再DOM建立以后给事件添加监听器,仅需在渲染的时候提供监听器便可。性能

用ES6的class定义一个组件的时候,事件监听器是做为一个类方法存在的。 例以下面的Toggle组件,能够在“ON”和“OFF”之间切换: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')
);

关于JSX回调里面的那个thiscode

在js里面,类方法默认是没有绑定(bound)的,加入你忘记了绑定this.handleClick,而后把它传给onClick,当函数被调用的时候,this将会是undefinedhtm

这不是React的特有行为,能够参考这篇文章。 一般,在使用方法的时候,后面没有加(),例如onClick={this.handleClick},这时你就要绑定这个方法。blog

若是你不想调用bind,仍是有两种方法能够绕过的。

第一种是使用实验性的属性初始化语法(property initializer syntax),用属性初始化来绑定回调函数:

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  // 确保'this'和handleClick绑定,这仍是实验性的语法
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

这个语法在React里面是默承认用的。

第二种方法是使用箭头函数(arrow function)。

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    // 确保'this'和handleClick绑定
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

这种语法的问题是,每次渲染LoggingButton的时候,都会建立不一样的回调函数。 大部分状况下,这是没有问题的。可是,若是这个回调函数是做为一个prop传递给下层组件的话,这些组件会重复渲染。 一般的推荐方法是在constructor里面绑定,以免这种性能问题。

参考连接:

  1. React Doc:handling events
相关文章
相关标签/搜索