728x90
⭐ React Event
- JavaScript에서의 이벤트를 React에서도 사용 할 수 있습니다.
1. 단계 1
class CounterText extends React.Component {
render() {
let textStyle = {
paddingBottom: 20,
fontSize: 36,
color: "#333"
};
return (
<div style={textStyle}>
{this.props.countProps}
</div>
)
}
}
class App2 extends React.Component {
constructor(props) {
super(props);
this.state= {
count: 0
}
}
countPlus() {
this.setState({
count: this.state.count +1
});
}
countMinus() {
this.setState({
count: this.state.count -1
})
}
render() {
let backgroundStyle = {
display: "inline-block",
padding: 20,
textAlign: "center",
backgroundColor: "#f4f4f4",
borderRadius: 10
}
let buttonStyle = {
margin: 2,
width: 40,
height: 30,
textAlign: "center",
fontSize: 14,
fontWeight: "bold",
color: "#666"
}
return (
<div style={backgroundStyle}>
<CounterText countProps={this.state.count}></CounterText>
<button onClick={this.countPlus} style={buttonStyle}>+</button>
<button onClick={this.countMinus} style={buttonStyle}>-</button>
</div>
)
}
}
root.render (
<App2></App2>
)
- 해석
countPlus(){
this.setState({
count: this.state.count+1
});
}
countMinus(){
this.setState({
count: this.state.count-1
});
}
countPlus(), countMinus() 함수에서의 this는 컴포넌트를 참조할 수 없습니다. 따라서 버튼을
클릭하더라도 숫자가 증가되거나 감소되지 않습니다
2. 단계 2
- 해결 방법 1 : 화살표 함수 사용
countPlus=() => {
this.setState({
count: this.state.count+1
});
};
countMinus=() => {
this.setState({
count: this.state.count-1
});
}
- 해결 방법 2 : bind(this) 사용
return(
<div style={backgroundStyle}>
<CounterText countPros={this.state.count} />
<button onClick={this.countPlus.bind(this)} style={buttonStyle}>+</button>
<button onClick={this.countMinus.bind(this)} style={buttonStyle}>-</button>
</div>
);
728x90
'React' 카테고리의 다른 글
React STEP 20 - Create React App - 2 (0) | 2025.02.10 |
---|---|
React STEP 19 - Create React App - 1 (0) | 2025.02.10 |
React STEP 17 - JSX에서 배열 사용 (0) | 2025.02.10 |
React STEP 16 - State - 2 (0) | 2025.02.10 |
React STEP 15 - State - 1 (1) | 2025.02.10 |