【译】Handling Events

发布时间:2019-08-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【译】Handling Events脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是react官方文档的个人翻译,如有翻译错误,请多多指出
原文地址:https://facebook.github.io/re...

Handling events wITh React elements is very similar to handling events on DOM elements.
处理React元素事件跟处理DOM元素事件很相似
There are some syntactic differences:
但有一下一些语法不同:
React events are named using camelCase, rather than lowercase.
React事件使用驼峰式命名的,而不是全小写。

With JSX you pass a function as the event handler, rather than a string.
JSX里你要传递函数给事件处理,而不是字符串

For example, the HTML:
HTML的话:

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

is slightly different in React:
React不同的语法:

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

Another difference is that you cannot return false to prevent default behavior in React.
另一个不同就是你不能返回false来阻止默认事件。

You must call PReventDefault explicitly.
你必须显示地调用preventDefault

For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:
举个例子,如果用HTML,你能这样写来阻止默认的链接行为来打开一个新的页面:

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

In React, this could instead be:
在React, 我们要这样做:

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

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

Here, e is a synthetic event.
这里的e是合成事件。

React defines these synthetic events according to the W3C spec, so you don't need to worry about cross-browser compatibility. See the SyntheticEvent reference guide to learn more.
React定义这些合成事件是根据W3C标准的,所以你不需要担心浏览器兼容问题。学习更多的合成事件

When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created.
当你用React的时候,当dom被创建的时候,你一般都不需要调用addEventListener来添加监听器到dom上。
Instead, just provide a listener when the element is initially rendered.
相反,只需要添加一个监听器当元素最初被渲染。

When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class.
当你用es6class定义一个组件的时候,一个通常的模式是在class上把事件处理定义一个方法。
For example, this Toggle component renders a button that lets the user toggle between "ON" and "OFF" states:
举个例子,Toggle组件渲染一个能让用于切换开关的按钮:

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')
);

You have to be careful about the meaning of this in JSX callbacks.
你必须留意一下JSX的会回调中的this的指向。
In JavaScript, class methods are not bound by default.
在JavsScript,类方法不是默认被绑定的。
If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
如果你忘了绑定this.handleClick并且传递到onClick事件里,当函数被调用的时候,this会返回undefined

This is not React-specific behavior; it is a part of how functions work in JavaScript.
这不是React特定的行为,这是Javascript中函数怎么工作的一部分。
Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.
通常来讲,如果你指向一个方法没有()在后面,例如onClick={this.handleClick},你应该绑定这方法。

If calling bind annoys you, there are two ways you can get around this.
如果你被经常要bind惹恼了,下面有两种方式来帮你绕过他。
If you are using the experimental property initializer syntax, you can use property initializers to correctly bind callbacks:
如果你使用实验性属性初始化语法,你能用这方法来正确绑定回调函数的绑定:

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>
    );
  }
}

This syntax is enabled by default in Create React App.
这语法在Create React App中默认支持。

If you aren't using property initializer syntax, you can use an arrow function in the callback:
如果你没有用这种属性初始化语法,你能用箭头函数来处理回调函数:

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>
    );
  }
}

打开试试
The problem with this syntax is that a different callback is created each time the LoggingButton renders.
这种语法的问题是,每次LoggingButton渲染的时候都会创建一个不同的回调。

In most cases, this is fine.
在大多数情况下还好。

However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering.
然而,如果这回调函数是作为一个props传递到更下一级的组件中的时候,些组件可能会做一个额外的重新渲染。

We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.
通常我们会要求在constructor或者用属性初始化语法来避免这种性能问题。

脚本宝典总结

以上是脚本宝典为你收集整理的【译】Handling Events全部内容,希望文章能够帮你解决【译】Handling Events所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。