
<button onclick = "activate()"> Activate </button>DOM์์๋ ํด๋ฆญ ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํ๋ ํจ์๋ฅผ DOM CLICK์ ํตํด์ ์ฒ๋ฆฌ
<button onClick={activate}> Activate </button>onClick(์นด๋ฉ ์ผ์ด์ค)์ผ๋ก ๋ํ๋๊ณ , ํจ์ ๊ทธ๋๋ก ์ฒ๋ฆฌ
class Toggle extends React.Component {
constructor(props){
super(props);
this.state = {isToggleOn: true };
//callback์์ 'this'๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์๋ ๋ฐ์ธ๋๋ฅผ ํ์์ ์ผ๋ก ํด์ค์ผ ํจ
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setStateprevState => ({
isToogleOn: !prevState.isToggleOn
}));
}
render(){
return(
<button onClick = {this.handleClick}>
{this.state.isToggleOn ? '์ผ์ง' : '๊บผ์ง' }
</button>
);
}
}
bind => JS์์๋ ๊ธฐ๋ณธ์ ์ผ๋ก Class ํจ์๋ค์ด ๋ฐ์ธ๋ ๋์ง ์์์, this๋ฅผ ์ฌ์ฉํ ๋ bind๋ฅผ ํ์ง ์์ผ๋ฉด global scope์์ ํธ์ถ์ด ๋จ.
๊ทธ๋ฌ๋, global scope์์๋ ํจ์๊ฐ ์ ์๋์ง ์์ผ๋ฏ๋ก undefinded๋ก ๋ํ๋จ
์ฆ, ํจ์์ ์ด๋ฆ ๋ค์ ๊ดํธ ์์ด ์ฌ์ฉํ๋ ค๋ฉด ๋ฌด์กฐ๊ฑด bind!
class MyButton extends React.Component {
handeClick= () => {
console.log('this is:', this);
}
render() {
return(
<button onClick={this.handleClick}>
ํด๋ฆญ
</button>
);
}
class myButton extends React.Component {
handleClick() {
console.log('this is', this);
}
render(){
return(
<button onClick={()=> this.handleClick()}>
ํด๋ฆญ
</button>
);
}
์ฑ๋ฅ๋ฌธ์ ๊ฐ ์์ผ๋ฏ๋ก 1,2๋ฒ ์ฃผ๋ก ์ฌ์ฉํ๋ ๊ฒ์ด ๋ฐ๋์ง
function Toggle(props){
const [isToggleOn, setIsToggleOn] = useState(true);
function handleClick() {
setIsToggleOn((isToggleOn) => !isToggleOn));
}
return(
<button onClick = {handleClick}>
{this.state.isToggleOn ? '์ผ์ง' : '๊บผ์ง' }
</button>
);
}
function Toggle(props){
const [isToggleOn, setIsToggleOn] = useState(true);
const handelClick=() => {
setIsToggleOn((isToggleOn) => !isToggleOn);
}
return(
<button onClick = {handleClick}>
{this.state.isToggleOn ? '์ผ์ง' : '๊บผ์ง' }
</button>
);
}
์ด๋๋ onClick์ this๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ๊ณง๋ฐ๋ก ์ ์ํ ํจ์๋ฅผ ๋ฃ์ด์ค!
<button onClick ={(event) => this.deleteItem(id, event)}>์ญ์ ํ๊ธฐ<button>
//arrow function
<button onClick={this.deleteItem.bind(this, id)}>์ญ์ ํ๊ธฐ</button>
//bind ์ฌ์ฉ
funciton MyButton(props){
const handleDelete = (id, event) => {
console.log(id, event.target);
};
return(
<button onClick={(event) => handleDelete(1, event)}>
์ญ์ ํ๊ธฐ
</button>
);
}
import React, {useState} from "react";
function ConfirmButton(props){
const [isConfirmed, setIsConfirmed] = useState(false);
const handleConfirm = () => {
setIsConfirmed((prevIsConfirmed) => !prevIsConfirmed);
};
// prev๋ ์ํ๋ฅผ ๋ณํํ๋ ๊ฒ!!
return (
<button onClick={handleConfirm} disabled={isConfirmed}>
{isConfirmed ? "ํ์ธ๋จ" : "ํ์ธํ๊ธฐ"}
</button>
)
};
export default ConfirmButton;