Released 2023-08-14

Modified 2023-08-14

Tech

766Words (4min read)

React class component 自定義表單資料處理

Title Image

Photo by React on React

導言 - Lead paragraph

在 Web 開發中,表單是用戶與應用之間交互的重要途徑。

默認情況下,點擊表單中的 "submit" 按鈕會觸發表單的默認提交行為,導致頁面刷新或將資料發送到後端。

然而有時我們需要更多的控制權,例如:在客戶端進行資料處理、驗證或者選擇性地獲取表單資料。

這時就可以藉助事件處理和 DOM 操作,自定義表單提交過程,以達到更靈活的資料處理目的。

範例 - Example

剛剛有提到當在表單中使用 submit 按鈕時,點擊按鈕會觸發表單的提交,並導致頁面刷新或將資料發送到後端。

瀏覽器會將所有表單元素的值都收集起來,包括 inputselecttextareabutton 等元素的值。

如果想要忽略某些特定的表單元素(例如 button),可以在提交表單時使用 JavaScript 來處理,而不是依賴瀏覽器的默認行為。

所以要使用 event.preventDefault() 來阻止表單的默認提交行為,然後利用 event.target.elements 來遍歷表單元素並取得需要的元素資料。

主範例
使用到 CheckedBox 時

當有使用到 CheckedBox 時,可以將遍歷部份加上特別處理:

for (let i = 0; i < formElements.length; i++) {
    const element = formElements[i];

    if (element.type === 'checkbox') {
        formData[element.name] = element.checked;
    } else if (element.type !== 'submit' && element.type !== 'button') {
        formData[element.name] = element.value;
    }
}
CheckedBox 注意事項與範例

而在 React 中,Form.Checktype 設置為 'checkbox' 時,默認情況下無論是否勾選,value 都會設置為 'on'。如果希望取得 truefalse,可使用 checked 屬性來判斷是否被勾選,而不是使用 value 屬性。

單個 Checked 轉換範例:

import React from 'react';

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      W1Checked: false, // 初始化為未勾選
    };
  }

  handleCheckboxChange = (event) => {
    const { name, checked } = event.target;
    this.setState({ [name]: checked });
  };

  render() {
    return (
      <form>
        <Form.Check
          type='checkbox'
          name='W1'
          label='星期一'
          className='me-2 me-md-3'
          checked={this.state.W1Checked}
          onChange={this.handleCheckboxChange}
        />
      </form>
    );
  }
}

export default MyForm;

複合 Checked 轉換範例:

import React from 'react';

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkboxes: {
        W1: false,
        W2: false,
        W3: false,
        W4: false,
        W5: false,
        W6: false,
        W7: false,
      },
    };
  }

  handleCheckboxChange = (event) => {
    const { name, checked } = event.target;
    this.setState((prevState) => ({
      checkboxes: {
        ...prevState.checkboxes,
        [name]: checked,
      },
    }));
  };

  render() {
    const weekdays = [
      { name: 'W1', label: '星期一' },
      { name: 'W2', label: '星期二' },
      { name: 'W3', label: '星期三' },
      { name: 'W4', label: '星期四' },
      { name: 'W5', label: '星期五' },
      { name: 'W6', label: '星期六' },
      { name: 'W7', label: '星期日' },
    ];

    return (
      <form>
        {weekdays.map((day) => (
          <Form.Check
            key={day.name}
            type='checkbox'
            name={day.name}
            label={day.label}
            className='me-2 me-md-3'
            checked={this.state.checkboxes[day.name]}
            onChange={this.handleCheckboxChange}
          />
        ))}
      </form>
    );
  }
}

export default MyForm;

結論 - Concluding

儘管這個方法在處理小型表單時可能是可行的,但在處理複雜的表單以及表單驗證和資料轉換方面可能會變得複雜。

React class component 自定義表單資料處理

https:///en/blog/88

Author

Kama

Read more from Tech
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.