当前位置: 首页 > news >正文

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;

http://www.xdnf.cn/news/1130707.html

相关文章:

  • 自动控制原理知识地图:舵轮、路径与导航图
  • 2025年C++后端开发高频面试题深度解析:线程安全LRU缓存设计与实现
  • C# StringBuilder源码分析
  • 2025年Java最新社招面试八股文+技术场景题(金九银十)
  • Hadoop架构演进:从1.0到2.0的深度对比与优化解析
  • Hadoop(二)
  • QT技巧之快速搭建串口收发平台
  • Taro.getRandomValues() 用法详解
  • 有哪些好用的原型设计软件?墨刀、Axure等测评对比
  • Elasticsearch+Logstash+Kibana部署
  • Taro.eventCenter 用法详解与实战
  • 深入核心:理解Spring Boot的三大基石:起步依赖、自动配置与内嵌容器
  • 【Qt+error】error: use of undeclared identifier ‘MainWindow
  • uniapp各端通过webview实现互相通信
  • qt 中英文翻译 如何配置和使用
  • Spring AI 系列之十三 - RAG-加载本地嵌入模型
  • 在 CentOS 8 上彻底卸载 Kubernetes(k8s)
  • k8s之持久化存储流程
  • JavaScript 异步编程的终极指南:从回调到 Promise、Async/Await
  • 深入解析Linux进程地址空间与虚拟内存管理
  • vivo S30评测:用设计诠释科技,以性能书写情怀
  • 电脑安装 Win10 提示无法在当前分区上安装Windows的解决办法
  • openEuler 22.03 LTS Rootless Docker 安装指南
  • Apache IoTDB(1):时序数据库介绍与单机版安装部署指南
  • 免费MCP服务:Excel CSV 转 JSON MCP by WTSolutions 文档
  • 计算机网络:(九)网络层(下)超详细讲解互联网的路由选择协议、IPV6与IP多播
  • 微服务中token鉴权设计的4种方式
  • STM32 | 定时器 PWM 呼吸灯
  • Python 程序设计讲义(2):Python 概述
  • kube-proxy 中 IPVS 与 iptables