728x90
반응형
Event의 정의 및 Event 다루기
Event
특정 사건
- 예시 : 사용자가 버튼을 클릭한 사건
바인딩 사용하기
class Toggle extends React.Component { constructor(props) { super(props); this.state = { isToggleOn: True }; // callback에서 `this`를 사용하기 위해서는 바인딩을 필수적으로 해줘야 합니다. this.handleClick = this.handleClick.bind(this); } // 바인딩 사용 handleClick() { this. setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? '켜짐' : '꺼짐'} </button> ); } }
바인딩 대신 Class fields syntax 사용
class MyButton extends React.Component { handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> 클릭 </button> ) } }
Arrow function 사용
class MyButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // 이렇게 하면 `this`가 바운드됩니다. return ( <button onClick={() => this.handleClick()}> 클릭 </button> ) } }
토글 컴포넌트를 함수 컴포넌트로 변환
function Toggle(props) { const [isToggleOn, setIsToggleOn] = useState(true); // 방법 1. 함수 안에 함수로 정의 function handleClick() { setIstToggleOn((isToggleOn) => !isToggleOn); } // 방법 2. arrow function을 사용하여 정의 const handleClick = () => { setIsToggleOn((isToggleOn) => !isToggleOn); } return ( <button onClick={handleClick}> {isToggleOn ? "켜짐" : "꺼짐"} </button> ); }
실습
import React from "react"
class ConfirmButton extends React.Component {
constructor(props) {
super(props)
this.state = {
isConfirmed: false,
}
}
this.handleConfirm = this.hanleConfirm.bind(this)
}
handleConfirm() {
this.setState(prevState) => ({
isConfirmed: !prevState.isConfirmed,
}))
}
render() {
return (
<button
onClick=(this.handleConfirm)
disabled=(this.state.isConfirmed)
>
{this.state.isConfirmed ? "확인됨" : "확인하기"}
</button>
)
}
}
export default ConfirmButton;
728x90
'개발 관련 학습 > React' 카테고리의 다른 글
[처음 만난 리액트] 섹션 10. List and Keys (0) | 2023.04.13 |
---|---|
[처음 만난 리액트] 섹션 9. Conditional Rendering (0) | 2023.03.13 |
[처음 만난 리액트] 섹션 7. Hooks (0) | 2023.03.10 |
[처음 만난 리액트] 섹션 6. State and Lifecycle (0) | 2023.03.10 |
[처음 만난 리액트] 섹션 5. Components and Props (0) | 2023.03.10 |