Form with React 用 React 做一份表單


Posted by Christy on 2021-12-04

本文為在學習 React router 與 Redux 之前,用 React 做表單並練習驗證功能

零、Description 功能描述

1. 版面參考

2. 表單驗證功能

3. React 官方 Forms 參考資料

4. 心得

用 React 做表單,要考慮的還是圍繞在 state 上面,「不能直接改 state」是 React 的核心價值

styled component 的類似 sass 的寫法還是不夠熟悉

一、切版:

1. RWD:

a. 背景:調整寬度

min-width: 900px;
width: 100%;

b. footer: 跟著背景的寬度走

c. 表格本人:注意寬高

max-width: 400px;
width: 100%;
max-height: 1000px;
height: 100%;

2. 關於 radio:

a. radio 無法顯示的錯誤寫法:

<RegisterRadio type="radio">躺在床上用想像力實作</RegisterRadio>

錯誤訊息:Error: input is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

解法:radio 類的 input 不能有 children,必須額外包起來

<RegisterLabel>
  <RegisterRadio type="radio"></RegisterRadio>
  躺在床上用想像力實作
</RegisterLabel>

b. name 相同,radio 才能單選

<RegisterLabel>
  <RegisterRadio type="radio" name="radio" />
  躺在床上用想像力實作
</RegisterLabel>
<RegisterLabel>
  <RegisterRadio type="radio" name="radio" />
  趴在地上滑手機找現成的
</RegisterLabel>

c. 點擊文字選中相對應 radio 按鈕

屬性必須是 label

const RegisterLabel = styled.label`
  line-height: 18px;
  font-size: 14px;
  margin: 15px 8px 0px 0px;
  display: flex;
  align-items: baseline;
`;

二、邏輯

1. 提交表單

有兩個重點,一個是「按下 submit 按鈕,檢查所有欄位是否為空」、「抓到輸入框的資料」

若有任一欄位為空,就出現提示訊息

要注意的地方:要用 onSubmit 的話,要把 div → form

2. 簡易驗證功能

在輸入框放上 type="number" & type="email" 會自動驗證是否為號碼或輸入字串有沒有包含 "@",一個簡單的驗證










Related Posts

Day 166

Day 166

老爸的私房錢

老爸的私房錢

DNS 是什麼?DNA 的兄弟嗎?

DNS 是什麼?DNA 的兄弟嗎?


Comments