Reputation: 65
import React from 'react';
import ChildComponent from './ChildComponent';
class SampleComponent extends React.Component {
sampleCallbackOne = () => {
// does something
};
sampleCallbackTwo = () => {
// does something
};
render() {
return (
<div>
<ChildComponent
propOne={this.sampleCallbackOne}
propTwo={() => this.sampleCallbackTwo()}
/>
</div>
);
}
}
export default SampleComponent;
In this example, I have an onClick event that I am handling and saw that I can successfully pass this into the props of the component in two ways.
I was wondering what exactly the difference is in both ways since they appear to function in the same manner?
Why do both ways work?
Upvotes: 1
Views: 516
Reputation: 15146
It is a common point that seems weird.
Refer details in document of handling-events
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
handleClick() {
console.log('this is:', this);
}
<button onClick={this.handleClick}>
If you don't add ()
behind this.handleClick
, you need to bind this
in your constructor, otherwise, you may want to use the next two methods:
which is enabled by default in Create React App
handleClick = () => {
console.log('this is:', this);
}
<button onClick={this.handleClick}>
which may cause performance problems and is not recommended, refer to the document above.
// The same on event handling but different in:
<button
onClick={(e) => this.deleteRow(id, e)} // automatically forwarded, implicitly
/>
<button
onClick={this.deleteRow.bind(this, id)} // explicitly
/>
Basically in our practice, we use public class field syntax with params which would look like below:
// No need to bind `this` in constructor
// Receiving params passed by elements as well as getting events of it
handler = (value: ValueType) => (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
// Do something with passed `value` and acquired `event`
}
<NumberFormat
...
onBlur={this.handler(someValue)} // Passing necessary params here
/>
We can share the handler function
by passing different params to it.
// Justify via keyword of stored content in flat data structure
handler = (value: string) => (event: React.ChangeEvent<HTMLInputElement>, id: ValidationItems) => {
// Do something with
// passed `value`,
// acquired `event`,
// for each element diffenced via `id`
};
<YourComponent
id="ID_1"
value={store.name1}
onChange={this.handler("name1")}
/>;
<YourComponent
id="ID_2"
value={store.name2}
onChange={this.handler("name2")}
/>;
// ... more similar input text fields
Upvotes: 1
Reputation: 1911
<ChildComponent
propOne={this.sampleCallbackOne}
propTwo={() => this.sampleCallbackTwo()}
/>
for propOne: here you are passing the reference of sampleCallbackOne
.
for propTwo: you are wrapping your sampleCallbackTwo
in another function.
In both the case you will get the same results
Upvotes: 1