'Assigning a callbacks to the react ref
Having such a simple react class component:
import React from "react";
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
myRef2 = (input) => {
console.log("myRef2")
}
myRef3 = (input) => {
console.log("myRef3")
}
render() {
return (
<div>
<input
id ="i1"
type="text"
ref={(input) => {
console.log("myRef1")
this.textInput = input; }
} />
<input
id ="i2"
type="text"
ref={this.myRef2} />
<input
id ="i3"
type="text"
ref={this.myRef3()} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
export default CustomTextInput
what is the difference between this 3 different ways of calling a refs:
1.
ref={(input) => { console.log("myRef1") this.textInput = input; } }
ref={this.myRef2}
ref={this.myRef3()}
Is there a difference between the #2 and #3 method? I'm i right that in the #2 case we assign the myRef2 function to the ref while in the #3 case we just call the myRef3 (parenthesis after the function name)?
Solution 1:[1]
#2 is a correct way of doing this :
<input
id ="i2"
type="text"
ref={this.myRef2} />
This means ,
<input
id ="i2"
type="text"
ref={()=>this.myRef2} />
While #3 means that when javascript code is executed , this.myRef3 function is called each time it is read:
<input
id ="i3"
type="text"
ref={this.myRef3()} />
<input
id ="i3"
type="text"
ref={ console.log("myRef3")} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shivam Sharma |
