当前位置: 首页 > 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.lryc.cn/news/590550.html

相关文章:

  • React 中 props 的最常用用法精选+useContext
  • H3CNE综合实验之机器人
  • Antd中使用Table集成 react-resizable实现可伸缩列
  • PowerJob集群机器数为0问题
  • 深度剖析 TDMQ RabbitMQ 版经典队列底层存储机制
  • vue页面不销毁的情况下再返回,总是执行created,而不触发 activated
  • QOpenGLWidget自定义控件— 2D点云显示(支持平移、放缩、绘制网格)
  • SpringBoot集成Minio存储文件,开发图片上传等接口
  • 【c++深入系列】:万字详解list(附模拟实现的list源码)
  • 【Fedora 42】Linux内核升级后,鼠标滚轮失灵,libinput的锅?
  • 开源 python 应用 开发(六)网络爬虫
  • ubuntu中拷贝docker容器中的文件到宿主机
  • IKE学习笔记
  • K8s 自定义调度器 Part1:通过 Scheduler Extender 实现自定义调度逻辑
  • AI产品经理面试宝典第28天:自动驾驶与智慧交通融合面试题与答法
  • Xshell 7.0.0111p.exe 下载安装教程 - 详细步骤指南(包含安装包)
  • Kotlin获取集合中的元素操作
  • Kotlin比较接口
  • 《工程伦理》分析报告二 无人驾驶
  • 利用pdfjs实现的pdf预览简单demo(包含翻页功能)
  • 用AI做带货视频评论分析进阶提分【Datawhale AI 夏令营】
  • Windows11怎样禁止应用开机启动
  • pytorch | minist手写数据集
  • 每日算法刷题Day49:7.16:leetcode 差分5道题,用时2h
  • C# 按照主题的订阅 按照类型的订阅
  • OCR 与 AI 图像识别:协同共生的智能双引擎
  • Spring MVC中@PathVariable的用法详解
  • Vue 3 中调用子组件方法
  • LLM大语言模型不适合统计算数,可以让大模型根据数据自己建表、插入数据、编写查询sql统计
  • 从洞察到行动:大数据+AI赋能消费者洞察