export const Counter = () => {
const onIncrease = () => {
console.log('+1')
}
const onDecrease = () => {
console.log('-1')
}
return (
<div>
<h1>0</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
)
}
useState
함수 : 컴포넌트에서 상태 관리 가능import React, { useState } from 'react'
export const Counter = () => {
const [number, setNumber] = useState(0)
const onIncrease = () => {
setNumber(number + 1)
}
const onDecrease = () => {
setNumber(number - 1)
}
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
)
}
import React, { useState } from 'react'
const [number, setNumber] = useState(0)
import React, { useState } from 'react'
export const Counter = () => {
const [number, setNumber] = useState(0)
const onIncrease = () => {
setNumber((prevNumber) => prevNumber + 1)
}
const onDecrease = () => {
setNumber((prevNumber) => prevNumber - 1)
}
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
)
}
해당 내용은 다음 자료를 참고했습니다.
https://react.vlpt.us/basic/07-useState.html