EventHandling
EventHandling
キャラメルボックスとして作成
onClick
, onMouseEnter
, ... イベントに接続されたjsコードは関数です
実際のDOM要素のみに適用
関数構成部品に適用(onClick)
function Component() {
return (
<div>
<button
onClick={() => {
console.log("hello")
}}
>
클릭
</button>
</div>
)
}
class Component extends React.Component{
state = { count: 0 }
render() {
return (
<div>
<p>{this.state.count}</p>
<button
onClick={() => {
console.log("hello")
this.setState((state) => ({
...state,
count: state.count + 1,
}))
}}
>
클릭
</button>
</div>
)
}
}
class Component extends React.Component{
state = { count: 0 }
render() {
return (
<div>
<p>{this.state.count}</p>
<button
onClick={() => {
}}
>
클릭
</button>
</div>
)
}
click() {
console.log("hello")
this.setState((state) => ({
...state,
count: state.count + 1,
}))
}
}
そうすると、thisはundefined
エラーが発生します.解決策
bind
作業を行う class Component extends React.Component{
state = { count: 0 }
constructor(props){
super(props);
this.click = this.click.bind(this)
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button
onClick={() => {
}}
>
클릭
</button>
</div>
)
}
click() {
console.log("hello")
this.setState((state) => ({
...state,
count: state.count + 1,
}))
}
}
使用 class Component extends React.Component {
state = {
count: 0,
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.click}>클릭</button>
</div>
)
}
click = () => {
console.log("hello")
this.setState((state) => ({
...state,
count: state.count + 1,
}))
}
}
Reference
この問題について(EventHandling), 我々は、より多くの情報をここで見つけました https://velog.io/@aksel26/EventHandlingテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol