react如何清空input
清空 React 中的 Input 方法
在 React 中清空 input 元素可以通过多种方式实现,以下是几种常见的方法:
方法一:使用受控组件(Controlled Component)
通过 state 控制 input 的值,将 state 设置为空字符串即可清空 input:
import React, { useState } from 'react';
function ClearInputExample() {
const [inputValue, setInputValue] = useState('');
const handleClear = () => {
setInputValue('');
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button onClick={handleClear}>Clear Input</button>
</div>
);
}
方法二:使用非受控组件(Uncontrolled Component)和 ref
通过 ref 直接操作 DOM 元素来清空 input:
import React, { useRef } from 'react';
function ClearInputWithRef() {
const inputRef = useRef(null);
const handleClear = () => {
inputRef.current.value = '';
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClear}>Clear Input</button>
</div>
);
}
方法三:使用表单重置
如果 input 位于表单中,可以通过重置表单来清空所有输入字段:
import React, { useRef } from 'react';
function ClearFormInput() {
const formRef = useRef(null);
const handleClear = () => {
formRef.current.reset();
};
return (
<form ref={formRef}>
<input type="text" />
<button type="button" onClick={handleClear}>Clear Input</button>
</form>
);
}
方法四:使用 defaultValue 和 key 属性
通过改变 key 值强制重新渲染组件,使 input 恢复默认值:

import React, { useState } from 'react';
function ClearInputWithKey() {
const [key, setKey] = useState(0);
const handleClear = () => {
setKey(prevKey => prevKey + 1);
};
return (
<div>
<input
key={key}
type="text"
defaultValue=""
/>
<button onClick={handleClear}>Clear Input</button>
</div>
);
}
注意事项
- 受控组件方法是最符合 React 设计模式的做法,推荐在大多数情况下使用
- 非受控组件方法在某些特定场景下可能更简单直接,但违背了 React 的数据流原则
- 表单重置方法适用于需要一次性清除多个输入字段的情况
- key 方法虽然有效,但会导致组件重新渲染,可能影响性能
选择哪种方法取决于具体的使用场景和项目需求。






