React -自定义hooks - 封装双向数据绑定
React主要是单向数据流,所以双向绑定不像Vue那样直接有v-model。那在React里通常是怎么做的呢?
react数据双向绑定
在 React 中实现双向数据绑定需要手动组合状态管理和事件处理,主要通过在输入元素上使用 value
属性和 onChange
事件的组合来实现。以下是具体实现方式:
import { useState } from 'react';function App() {const [inputValue, setInputValue] = useState('');// 双向绑定逻辑const handleChange = (e) => {setInputValue(e.target.value); // 输入变化时更新状态};return (<div><input type="text"value={inputValue} // 状态 → 视图onChange={handleChange} // 视图 → 状态/><p>Current Value: {inputValue}</p></div>);
}
如果我们页面中有许多的输入框,代码就会很繁琐,所以我们进行封装
封装双向数据绑定
新建hooks文件
import { useState } from "react";const resolveValue = (e:any)=>{return e?.target?.value??e?.value??e
}const useInput = (value: any) => {const [state, setState] = useState(value);const bindState = {value: state,onChange: (e: React.ChangeEvent<HTMLInputElement>) => {setState(resolveValue(e));},onInput: (e: React.ChangeEvent<HTMLInputElement>) => {setState(resolveValue(e));},};return [state,bindState,setState,];
};
export { useInput }
页面使用
import { Input, Select } from "antd";
import { useEffect } from "react";
import { useInput } from "@/hooks/index"; //引入封装的双向绑定hooks
const Login = () => {const [username, bindUsername, setUsername] = useInput("");const [userPassword, binduserPassword, setuserPassword] = useInput("");const [userSelect, binduserSelect, setuserSelect] = useInput([]);useEffect(() => {console.log(username);console.log(userPassword);console.log(userSelect);}, [username, userPassword, userSelect]);return (<div><Input placeholder="username" {...bindUsername} /><Input placeholder="userpassword" {...binduserPassword} /><Selectmode="multiple"placeholder="Please select"style={{ width: "200px" }}{...binduserSelect}options={[{ value: "Ava Swift", label: "Ava Swift" },{ value: "Cole Reed", label: "Cole Reed" },{ value: "Mia Blake", label: "Mia Blake" },{ value: "Jake Stone", label: "Jake Stone" },]}/></div>);
};
export default Login;