资讯专栏INFORMATION COLUMN

【译】Handling Events

sugarmo / 1186人阅读

摘要:如果你使用实验性属性初始化语法,你能用这方法来正确绑定回调函数的绑定这语法在中默认支持。然而,如果这回调函数是作为一个传递到更下一级的组件中的时候,些组件可能会做一个额外的重新渲染。

下面是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的话:

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

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,你能这样写来阻止默认的链接行为来打开一个新的页面:


  Click me

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

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

  return (
    
      Click me
    
  );
}

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.
当你用es6的class定义一个组件的时候,一个通常的模式是在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 (
      
    );
  }
}

ReactDOM.render(
  ,
  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 (
      
    );
  }
}

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

打开试试
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或者用属性初始化语法来避免这种性能问题。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/81910.html

相关文章

  • 】 WebSocket 协议第八章——错误处理(Error Handling

    摘要:概述本文为协议的第八章,本文翻译的主要内容为错误处理相关内容。这个规则在建立连接开始握手和后续的数据交换时都生效。 概述 本文为 WebSocket 协议的第八章,本文翻译的主要内容为 WebSocket 错误处理相关内容。 错误处理(协议正文) 8.1 处理 UTF-8 数据错误 当终端按照 UTF-8 的格式来解析一个字节流,但是发现这个字节流不是 UTF-8 编码,或者说不是一个...

    baiy 评论0 收藏0
  • 】Java异常处理策略

    摘要:指示该错误是否严重,此属性会在该异常根据错误的上下文遍历堆栈时进行更新,严重性会指示异常捕获代码是应该停止程序还是该继续处理。引发异常在检测到错误并无法从中恢复时,异常将向上传播到调用堆栈,直到到达处理它的某个块。 翻译:疯狂的技术宅 原文标题:Exception handling strategy 原文链接:http://programmergate.com/exc...本文首发微信...

    cartoon 评论0 收藏0
  • WebSocket 协议 RFC 文档(全中文翻

    摘要:概述经过半年的捣鼓,终于将协议全篇翻译完成。现在将所有章节全部整理到一篇文章中,方便大家阅读。如果大家想看具体的翻译文档,可以去我的中查看。大家有相关类型的需要,建议大家可以尝试下。 概述 经过半年的捣鼓,终于将 WebSocket 协议(RFC6455)全篇翻译完成。现在将所有章节全部整理到一篇文章中,方便大家阅读。如果大家想看具体的翻译文档,可以去我的GitHub中查看。 具体章节...

    ghnor 评论0 收藏0
  • 】闭包并不神秘

    摘要:下面我们就初步尝试一下闭包现在来看一下发生了什么。于是,这种结构就被称作闭包。这就是闭包强大的地方。例如,如果我们可以在我们的计数器里面加一个名字我们可以往闭包里传一个参数可以看出来,在实现过程中不仅能记住局部变量,也记住了传进来的变量。 计数器 首先,从一个计数器开始。 var counter = 0; function increment() { counter = cou...

    sevi_stuo 评论0 收藏0
  • JavaScript 简介

    摘要:简介原文链接简称是一种轻量级,解释型的编程语言,其函数是一等公民。标准的目标是让任何一种程序设计语言能操控使用任何一种标记语言编写出的任何一份文档。核心规定了如何映射基于的文档结构,以便简化对文档的任意部分的访问和操作。 JavaScript 简介 原文链接 JavaScript ( 简称:JS ) 是一种 轻量级,解释型 的编程语言,其函数是一等公民。众所周知,它是用于网页开发的脚...

    URLOS 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<