WEB/REACT

[React] ์ด๋ฒคํŠธ ํ•ธ๋“ค๋ง

mingzoo 2020. 11. 30. 13:30

EVENT = ํŠน์ • '์‚ฌ๊ฑด'

 

๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ => ์‚ฌ์šฉ์ž๊ฐ€ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•œ ์‚ฌ๊ฑด

HTML

<button onclick = "activateLasers()">
	Activate Lasers
</button>

HTML

  • onclick์ด ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ ธ์žˆ์Œ
  • ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•  ํ•จ์ˆ˜๋ฅผ ํฐ๋”ฐ์˜ดํ‘œ("")๋กœ ๋ฌถ์–ด์„œ ํ‘œํ˜„ํ•ด๋†“์•˜์Œ
React

<button onClick = {activateLasers}>
	Activate Lasers
</button>

 

React

  • onClick์˜ C๊ฐ€ HTML๊ณผ ๋‹ค๋ฅด๊ฒŒ ๋Œ€๋ฌธ์ž๋กœ ๋‚˜ํƒ€๋ƒ„
  • ์ด๋ฒคํŠธ๋ฅผ ์ „๋‹ฌํ•  ๋•Œ ๋ฌธ์ž์—ด์ด ์•„๋‹Œ ํ•จ์ˆ˜(์ด๋ฒคํŠธ์ฒ˜๋ฆฌ ํ•จ์ˆ˜)๋ฅผ ์ „๋‹ฌ

 

Camel Case

 

ํŒŒ์ผ, ๋ณ€์ˆ˜, ํ•จ์ˆ˜ ๋“ฑ ๋Œ€์ƒ์˜ ์ด๋ฆ„์„ ๋„์–ด์“ฐ๊ธฐ ์—†์ด ์ง“๊ธฐ ์œ„ํ•จ

๋ฆฌ์•กํŠธ์˜ ํ•จ์ˆ˜ ํ•ธ๋“ค๋ง์—์„œ ์‚ฌ์šฉ๋จ

 


Event handler = Event Listener

์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜

์–ด๋–ค ์‚ฌ๊ฑด์ด ๋ฐœ์ƒํ•˜๋ฉด, ์‚ฌ๊ฑด์„ ์ฒ˜๋ฆฌํ•˜๋Š” ์—ญํ• 

 

์ด๋ฒคํŠธ ํ•ธ๋“ค๋ง ๊ณต์‹ ๋ฌธ์„œ

 

์‰ฌ์šด ์˜ˆ์‹œ(onClick ์‚ฌ์šฉ)

 

JS)

onClick = "ํด๋ฆญํ•  ๋•Œ ์‹คํ–‰ํ•  JS"

 

React)

onClick = {ํด๋ฆญํ•  ๋•Œ ์‹คํ–‰ํ•  JS}

onClick = { ()=>{์‹คํ–‰ํ•  ๋‚ด์šฉ}}

 

1. ๐Ÿ‘๐Ÿป ๋ˆ„๋ฅผ ๋•Œ๋งˆ๋‹ค ์ฝ˜์†” ์ฐฝ์— 1 ๋„์šฐ๊ธฐ

<span onClick = {()=>console.log(1)}}> ๐Ÿ‘๐Ÿป </span>

 

2. ๐Ÿ‘๐Ÿป๋ˆ„๋ฅผ ๋•Œ๋งˆ๋‹ค 1 ์ฆ๊ฐ€ ์‹œํ‚ค๊ธฐ

import React, {useState} from 'react';

let[like, like_change] = useState(0);

<span onClick={()=>{like_change(like+1)}}>๐Ÿ‘๐Ÿป{like}</span>

state๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” import React, {useState} from 'react'; ๋ฅผ ๊ผญ ์ถ”๊ฐ€ํ•ด์ฃผ๊ธฐ

 

let[like,like_change] = useState(0); ์—์„œ

like๋Š” state์ด๊ณ , like_change๋Š” state๋ณ€๊ฒฝํ•จ์ˆ˜์ด๋‹ค.

useState(0)์—์„œ์˜ 0์€ state์˜ ์ดˆ๊ธฐ๊ฐ’

 

 

๐Ÿ˜Ÿ์ฃผ์˜์‚ฌํ•ญ

state๋Š” ๊ทธ๋ƒฅ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๊ณ , state๋ณ€๊ฒฝํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ state๋ณ€๊ฒฝํ•จ์ˆ˜(state๋ฅผ ๋Œ€์ฒดํ•  ๋ฐ์ดํ„ฐ)๋กœ ๋ณ€๊ฒฝํ•ด์ฃผ๋ฉด๋จ

728x90