react 绑定函数
by Tiffany White
蒂芙尼·怀特(Tiffany White)
在没有构造函数的情况下如何在React中绑定this
(How to bind this
in React without a Constructor)
This post was originally published on my blog.
该帖子最初发布在我的博客上 。
this
in React is a reference to the current component. Usually this
in React is bound to its built-in methods. When you want to update state or use an event handler on a form, you could do something like this:
this
在React中是对当前组件的引用。 通常this
在React必将以其内置的方法。 当您要更新状态或在表单上使用事件处理程序时,可以执行以下操作:
where this.someInput
is passing state to whichever React component you are rendering.
这里this.someInput
正在将状态传递给您正在渲染的任何React组件。
Unfortunately, though, React doesn’t auto-bind this
to custom methods. This means that if I wanted to manipulate the DOM by getting some input, which you can't do as you can with normal JavaScript, I would create a ref
to do whatever DOM tinkering I wanted.
但是不幸的是,React不会自动this
绑定到自定义方法。 这意味着,如果我想通过获取一些输入来操纵DOM,而这是普通JavaScript所无法做到的,那么我将创建一个ref
来完成我想要的DOM修改。
But because React doesn’t auto-bind this
, the following code would output undefined when logged:
但是由于React不会自动绑定this
,因此以下代码在登录时将输出undefined:
In order to avoid this, we could use the constructor
function to render the component or get the state we want:
为了避免这种情况,我们可以使用constructor
函数来呈现组件或获取我们想要的状态:
While this is a decent way to render a ref on a component, what if you wanted to bind several custom methods in one component? It would get pretty messy…
虽然这是在组件上呈现引用的一种不错的方法,但是如果您想在一个组件中绑定多个自定义方法怎么办? 会变得很乱...
You get the idea.
你明白了。
Instead, we can bind this
to custom React methods by declaring a method by assigning it to an arrow function:
相反,我们可以结合this
定制阵营由它分配给一个箭头函数声明的方法方法:
which will allow us to bind the value of this
to the SomeComponent
component.
这将使我们的值绑定this
给SomeComponent
组件。
希望这可以帮助! (Hope This Helps!)
ES6 gave us classes and constructors and React utilized them right away. You don’t always need a constructor, and it helps to know when to use one and when not to.
ES6给了我们类和构造函数,React立即使用了它们。 您并不总是需要构造函数,它有助于知道何时使用一个构造函数,何时不使用它。
当你在这里! (While you’re here!)
I write unobtrusive letters from time to time. They are dev letters that are a bit more intimate than regular newsletters. Sign up if you want. No worries.
我不时写些不引人注目的信件。 它们是开发人员信函,比常规新闻更亲密。 如果需要,请注册。 别担心。
翻译自: https://www.freecodecamp.org/news/how-to-bind-this-in-react-without-a-constructor-3a694f5d1b34/
react 绑定函数