// This is wrong
<button onclick="ClickButton()">
//This is right
<button onClick="ClickButton()">
// This is normal case
<a href="#" onclick="return false"></a>
// In reactJS, do like this
function ActionLink() {
function handleClick(event) {
event.preventDefault();
}
return (
<a href="#" onClick={handleClick}></a>
);
}
In javascript, Class method isn't binded to class. So we have to bind class method by using bind()
method. Like below.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
// This part is to bind handleClick() as test()
this.test= this.handleClick.bind(this);
}
handleClick() {
this.setState((state) => ({
isToggleOn: !state.isToggleOn,
}));
}
render() {
return (
<div>
<button onClick={this.test}>{this.state.isToggleOn ? "On" : "Off"}</button>
</div>
);
}
}
When we call "callback function" in reactJS, we have two choices. One is using bind()
method like above, and the other is using "arrow function."
// Using bind()
<button onClick={this.handleClick.bind(this)}></button>
// Arrow function
<button onClick={(event) => this.handleClick(event)}></button>
And to transfer additional arguments, do like this.
// Using bind()
<button onClick={this.handleClick.bind(this, argument1)}></button>
// Arrow function
<button onClick={(event) => this.handleClick(argument1, event)}></button>
If we use arrow function, we have to transfer event
argument next to argument1
. But we don't have to do that in using bind()
. It automatically transfer additional argument to class method.
javascript에서 class method가 binding 되어있지 않은 부분에 대해 알 수 있었던 섹션이었다. 아직 es6에 대해 공부하지 않아 헷갈리는 부분이 있어서 시간을 투자할 수 밖에 없었고 다행히 잘 이해가 됐다. 이렇게 디테일한 부분에 대해서 하나하나 쌓아가는게 실력에 많은 도움이 될 것이라 생각한다.