昨天我們學了props,今天換到元件自己的資料來源——state。有了state,你的畫面才能對使用者操作做出反應:輸入文字、點擊按鈕、切換開關、增刪清單…通通靠它。
import { useState } from 'react'
export default function Counter(){
const [count,setCount] = useState(0) // 初始值0
return (
<div className="p-6">
<p>目前:{count}</p>
<button
className="px-3 py-2 rounded bg-blue-600 text-white"
onClick={()=>setCount(count+1)}
>
+1
</button>
</div>
)
}
這裡count是state變數,setCount是修改它的函式。
React常見的「受控表單」:輸入值即綁定到state。
import { useState } from 'react'
export default function Form(){
const [name,setName] = useState('')
const submit=(e)=>{
e.preventDefault()
alert(`送出:${name}`)
}
return (
<form onSubmit={submit} className="p-6 space-y-3">
<input
className="border rounded px-3 py-2 w-full"
placeholder="你的名字"
value={name}
onChange={e=>setName(e.target.value)}
/>
<button className="px-4 py-2 rounded bg-blue-600 text-white">送出</button>
</form>
)
}