프론트엔드
[React] 이벤트 핸들러로 파라미터 전달하기
cs09g
2020. 10. 28. 23:00
반응형
1. this 바인딩과 함께 전달
class MyComponent extends React.Component {
myMethod(param, e) {
console.log(param); // 'someParam'
console.log(e); // SyntheticEvent
}
render() {
return (
<button onClick={this.myMethod.bind(this, 'someParam')}></button> {/* this 바인딩과 함께 전달 */}
);
}
}
2. arrow function 활용
class MyComponent extends React.Component {
myMethod(param, e) {
console.log(param); // 'someParam'
console.log(e); // undefined
}
render() {
return (
<button onClick={() => {this.myMethod('someParam')}></button> {/* arrow function 활용 */}
);
}
}
React 합성 이벤트가 필요한 경우 명시해주어야 한다.
class MyComponent extends React.Component {
myMethod(param, e) {
console.log(param); // 'someParam'
console.log(e); // SyntheticEvent
}
render() {
return (
<button onClick={(e) => {this.myMethod('someParam', e)}></button> {/* arrow function 활용 */}
);
}
}
반응형