类似 vue 中的 v-model
受控组件
有value属性,将表单值的获取和更新都交由react中的state来管理的组件
import { useState } from "react";
export default function Father() {
const [msg, setmsg] = useState("");
const handleChange = (e) => {
setmsg(e.target.value);
};
return (
<div>
<p> {msg}</p>
<input type="text" value={msg} onChange={handleChange} />
</div>
);
}
非受控组件
没有value属性,通过操作DOM来获取表单数据的组件
import { useRef } from "react";
export default function Father() {
const Ref_input = useRef(null);
function getFileInfo() {
console.log(Ref_input.current && Ref_input.current.files);
}
return (
<div>
<input type="file" ref={Ref_input} />
<button onClick={getFileInfo}>获取文件信息</button>
</div>
);
}
单行输入框 input
<input value={msg} onChange={changeHandler} />
import { useState } from "react";
const [msg, setMsg] = useState("你好");
function changeHandler(e) {
setMsg(() => e.target.value);
}
多行输入框 textarea
<textarea value={msg} onChange={changeHandler} />
import { useState } from "react";
const [msg, setMsg] = useState("你好");
function changeHandler(e) {
setMsg(() => e.target.value);
}
下拉选择 select
<select value={city} onChange={changeHandler} >
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="wuhan">武汉</option>
</select>
import { useState } from "react";
const [city, setCity] = useState("beijing");
function changeHandler(e) {
setCity(() => e.target.value);
}
单选 radio
<label htmlFor="radio_male">男</label>
<input id="radio_male" type="radio" name="gender" value='male' checked={gender === 'male'} onChange={changeHandler} />
<label htmlFor="radio_female">女</label>
<input id="radio_female" type="radio" name="gender" value='female' checked={gender === 'female'} onChange={changeHandler} />
import { useState } from "react";
const [gender, setGender] = useState('');
function changeHandler(e) {
setGender(() => e.target.value);
}
多选 checkbox
<input id="checkbox_apple" type="checkbox" name="fruit" value='apple' checked={fruitList.includes('apple')} onChange={changeHandler} />
<label htmlFor="checkbox_apple">苹果</label>
<input id="checkbox_orange" type="checkbox" name="fruit" value='orange' checked={fruitList.includes('orange')} onChange={changeHandler} />
<label htmlFor="checkbox_orange">橘子</label>
import { useState } from "react";
const [fruitList, setFruitList] = useState([]);
function changeHandler(e) {
let newValue = e.target.value;
if (fruitList.includes(newValue)) {
// 数组删除元素
setFruitList(fruitList.filter((item) => item !== newValue));
} else {
// 数组新增元素
setFruitList([...fruitList, newValue]);
}
}
标签 label
用 htmlFor 代替 for 来绑定其他表单元素
<label htmlFor="msgInput">消息:</label>
<input id="msgInput" value={msg} onChange={changeHandler} />