Ant Design 输入框 onChange 事件:只传修改过的值

在使用 Ant Design 的 Input 组件时,您可能需要在提交表单时,只传递用户实际修改过的输入框的值,而未修改的输入框传递空值。

您可以使用 state 来维护每个输入框的值,然后在传参时判断是否编辑过,如果未编辑过,则传空值。

示例代码

import React, { useState } from 'react';
import { Input } from 'antd';

const MyComponent = () => {
  const [input1Value, setInput1Value] = useState('');
  const [input2Value, setInput2Value] = useState('');
  const [input3Value, setInput3Value] = useState('');

  const handleInputChange = (event, setValue) => {
    setValue(event.target.value);
  };

  const handleSubmit = () => {
    // 判断是否编辑过,如果未编辑过,则传空值
    const value1 = input1Value !== '' ? input1Value : '';
    const value2 = input2Value !== '' ? input2Value : '';
    const value3 = input3Value !== '' ? input3Value : '';

    // 进行参数传递
    // ...
  };

  return (
    <div>
      <Input
        value={input1Value}
        onChange={(e) => handleInputChange(e, setInput1Value)}
      />
      <Input
        value={input2Value}
        onChange={(e) => handleInputChange(e, setInput2Value)}
      />
      <Input
        value={input3Value}
        onChange={(e) => handleInputChange(e, setInput3Value)}
      />

      <button onClick={handleSubmit}>提交</button>
    </div>
  );
};

export default MyComponent;

代码解释

  1. 使用 useState 创建 3 个状态变量 input1Valueinput2Valueinput3Value,分别用于保存 3 个输入框的值。

  2. handleInputChange 函数用于更新对应状态变量的值。

  3. handleSubmit 函数中,根据每个输入框的值是否为空来判断是否编辑过,如果未编辑过,则传空值。

通过以上做法,您可以实现只编辑某一个输入框时,其他输入框传空值的效果。


原文地址: https://www.cveoy.top/t/topic/o5Ci 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录