react如何设置input
设置 React Input 的基本方法
在 React 中,可以通过 useState 管理输入框的状态,并通过 onChange 事件更新值。
import React, { useState } from 'react';
function InputExample() {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="输入内容"
/>
);
}
export default InputExample;
受控组件 vs 非受控组件
受控组件:输入值由 React 状态管理(如上例)。
非受控组件:输入值由 DOM 自身管理,可通过 ref 获取值。
import React, { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = () => {
console.log(inputRef.current.value);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>提交</button>
</div>
);
}
表单处理
使用 form 标签时,可结合 onSubmit 事件管理输入数据。
function FormExample() {
const [formData, setFormData] = useState({ username: '', password: '' });
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
<button type="submit">提交</button>
</form>
);
}
常见输入类型
支持 HTML5 标准输入类型,如 text、password、email、number 等。
<input type="email" placeholder="邮箱" />
<input type="number" min="0" max="100" />
<input type="date" />
表单验证
可在 onChange 或 onSubmit 时进行校验。
const [error, setError] = useState('');
const validateInput = (value) => {
if (!value) {
setError('不能为空');
} else {
setError('');
}
};
样式和类名
通过 className 或内联样式设置输入框样式。
<input className="custom-input" style={{ border: '1px solid #ccc' }} />
高级功能
- 防抖:减少频繁触发
onChange事件。 - 自动聚焦:使用
autoFocus属性。 - 禁用状态:通过
disabled控制。
<input autoFocus disabled={isLoading} />






