返回
一招教您轻松清空 React Input 和时间输入框,实现独立操作!
前端
2024-02-13 10:39:22
在 React 中,Input 和时间输入框是常见的表单元素,用于收集用户输入的数据。在某些情况下,我们需要能够清空这些输入框的内容,以便用户重新输入数据。传统上,清空输入框可以通过使用 FormItem 来实现。
import { Form, Input, Button } from 'antd';
const MyForm = () => {
const [form] = Form.useForm();
const resetForm = () => {
form.resetFields();
};
return (
<Form form={form}>
<Input placeholder="Input" />
<Button onClick={resetForm}>重置</Button>
</Form>
);
};
但是,如果我们不使用 FormItem,而是单独使用 Input 和时间输入框,该如何清空它们的内容呢?
一种方法是使用 ref 来获取输入框元素,然后使用其 value
属性来设置其值为空。
import { useRef } from 'react';
const MyInput = () => {
const inputRef = useRef(null);
const resetInput = () => {
inputRef.current.value = '';
};
return (
<div>
<input ref={inputRef} placeholder="Input" />
<button onClick={resetInput}>重置</button>
</div>
);
};
另一种方法是使用状态来存储输入框的值,然后使用 useState
钩子来重置该状态。
import { useState } from 'react';
const MyInput = () => {
const [value, setValue] = useState('');
const resetInput = () => {
setValue('');
};
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} placeholder="Input" />
<button onClick={resetInput}>重置</button>
</div>
);
};
这两种方法都可以实现清空输入框的内容,但第二种方法更加灵活,因为它允许我们使用状态来控制输入框的值。这在我们需要在输入框中预填充数据或验证用户输入时非常有用。
当然,您还可以根据自己的需要,使用其他方法来实现清空输入框的内容。