iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
生成式 AI

30天用React打造AI工具箱系列 第 6

30天用React打造AI工具箱 Day6

  • 分享至 

  • xImage
  •  

30天用React打造AI工具箱 Day6

昨天我們學了props,今天換到元件自己的資料來源——state。有了state,你的畫面才能對使用者操作做出反應:輸入文字、點擊按鈕、切換開關、增刪清單…通通靠它。

什麼是state?

  • props是父層給的資料,子元件只能讀。
  • state是元件自己管理的資料,透過setState更新後會觸發重新渲染(render)。

usestate基本用法

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>
  )
}

上一篇
30天用React打造AI工具箱 Day5
下一篇
30天用React打造AI工具箱 Day7
系列文
30天用React打造AI工具箱8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言