且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么以及何时需要在React中绑定函数和eventHandler?

更新时间:2022-11-23 07:42:38

每个都不同,这取决于您的组件的设置方式

Each is different and it depends on how your component is set up

第一个即可。 .bind(this)用于将此上下文绑定到组件函数。 React ES6类不会自动绑定上下文,因此您必须显式绑定。有几种方法可以做到这一点, .bind(this)是一种方法。如果你不想使用那种方法,你可以

First. .bind(this) is used to bind your this context to your components function. React ES6 classes do not auto bind context so you must bind explicitly. There are a few ways to do that and .bind(this) is a way. if you don't want to use that method you can either

a。在你的构造函数中做绑定。 aka

a. in your constructor do the binding. aka

class SomeClass extends Component{
    constructor(){
        super();
        this.someEventHandler = this.someEventHandler.bind(this);
    }
    someEventHandler(event){
    }
    ....
} 

或b。在类胖箭头函数上创建自定义函数。 aka

or b. make your custom functions on the class fat arrow functions. aka

class SomeClass extends Component{
    someEventHandler = (event) => {
    }
    ....
}

这一切处理此上下文绑定。

this all deals with this context binding.

第二 onChange = {(event)=> {this.someEventHandler(event)} 使用内联lambda(胖箭头)函数包装组件处理函数,该函数可以提供一些额外的功能。假设你想为你的函数发送一个额外的参数,这是实现这个目标的一种方法。

Second. onChange={(event) => { this.someEventHandler(event) } is wrapping your components handler function with an inline lambda (fat arrow) function that can provide some additional functionality. Lets say you want to send an additional param to your function, this is a way to achieve that.

< input onChange = {(event )=> {this.someEventHandler(event,'username')}>

这是一种将附加参数传递给处理函数的方法如果需要。

this would be a way to pass an additional parameter to a handler function if desired.

第三次。您只是将函数作为回调函数传递,以便在单击事件发生时触发,没有其他参数

Third. You are just passing the function as the callback function to trigger when the click event happens, with no additional paramters

总结。这三个示例都与将处理函数传递给click事件有关。但是您可以添加不同的东西。第一个是关于你的这个上下文。第二个是关于如何将参数传递给你的处理函数。

To summarize. These three examples all are related to passing a handler function to a click event.. however there are different things you can add to that. the first is about your this context. the second is about how to pass arguments to your handler function.