1. camelCase 로만 사용 할 수 있다.
--> onClick, onMouseEnter
2. 이벤트에 연결된 JS 코드는 함수다.
--> 이벤트={함수}
3. 실제 DOM 요소들에만 사용 가능하다.
--> 리액트 컴포넌트에 사용하면, 그냥 props로 전달한다.
function Component() {
return (
<div>
<button
onClick={() =>{
console.log("클릭됨ㅋ");
}}
>
클릭해!
</button>
</div>
);
}
class MyComponent extends React.Component {
state = {
count: 0,
};
render() {
return (
<div>
<p>{this.state.count}</p>
<button
onClick={() => {
console.log("클릭됨ㅋ");
this.setState( state => ({...state, count: state.count + 1}));
}}
>
클릭해!
</button>
</div>
);
}
}
ReactDOM.render(<MyComponent/>, document.querySelector('#root'));
클릭해서 실행되는 함수부분을 따로 만들어 주자.
class ClassComp extends React.Component {
state = {
count: 0,
}
// binding 하는 방법 1
// constructor(props) {
// super(props);
// this.click = this.click.bind(this);
// }
render() {
return(
<div>
<h1>
<button
onClick={ this.click }>
{ this.props.message }
</button>
<p>{this.state.count}</p>
</h1>
</div>
)
}
// setState 가 제대로 binding 되어 있지 않다. binding 하는 해결방법은 두가지다.
// 하나는 위의 생성자에서 하는것이고, 다른 하나는 화살표 함수로 바꿔주는 것이다.
// click = () =>
click() {
this.setState( state => ({
...state,
count: state.count + 1
}))
}
static defaultProps = {
message: "클릭!",
}
}
ReactDOM.render(<ClassComp />, document.querySelector('#root'));