iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
生成式 AI

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

30天用React打造AI工具箱 Day10

  • 分享至 

  • xImage
  •  

30天用React打造AI工具箱 Day10

React受控表單:讓使用者輸入資料

到現在為止,我們已經能顯示清單,但清單內容都是寫死的。今天要學的是「受控表單」,也就是把輸入框的值和state連動,讓使用者能輸入資料並新增到清單。

什麼是「受控」?

在React中,輸入框的值(value)不是瀏覽器自己管,而是「由React的state決定」。

使用者輸入 → onChange事件觸發 → setState更新 → React重新render → value更新。
這樣React就能完全控制輸入框的值,這就是受控表單。

範例

import { useState } from 'react'

export default function NameForm(){
  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>
  )
}

這裡輸入框的值完全跟著name這個state走。

把表單和清單結合

昨天我們有一個TodoList,現在加上表單就能動態新增待辦:

import { useState } from 'react'

export default function TodoApp(){
  const [text,setText] = useState("")
  const [todos,setTodos] = useState([
    { id:1, text:"學React", done:false }
  ])

  const addTodo=(e)=>{
    e.preventDefault()
    const title=text.trim()
    if(!title) return
    setTodos(prev=>[
      ...prev,
      { id:Date.now(), text:title, done:false }
    ])
    setText("")
  }

  return (
    <div className="p-6 space-y-3">
      <form onSubmit={addTodo} className="flex gap-2">
        <input
          className="border rounded px-3 py-2 flex-1"
          placeholder="輸入待辦事項"
          value={text}
          onChange={e=>setText(e.target.value)}
        />
        <button className="px-4 py-2 rounded bg-blue-600 text-white">新增</button>
      </form>

      <ul className="space-y-2">
        {todos.map(todo=>(
          <li key={todo.id} className="p-2 border rounded">
            {todo.text}
          </li>
        ))}
      </ul>
    </div>
  )
}

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

尚未有邦友留言

立即登入留言