【antd】Switch,0和1,怎么办?

根据官方文档,Switch的值只可能是truefalse。但后端一般存储的是0和1,该怎么办?

方法一 转换接口数据

  1. 从接口来的数据 apiData={staus:1}
  2. 转化为表单 form={status:true}
  3. 再次转换传回接口 requestBody={staus:1}

方法二 封装Switch为NumericSwitch

示例代码来自AI

tsx 复制代码
import { Switch } from 'antd';

const NumericSwitch = ({ value, onChange, ...props }) => {
  return (
    <Switch
      {...props}
      checked={value === 1}
      onChange={(checked) => onChange(checked ? 1 : 0)}
    />
  );
};

方法三 使用react-vmodel

tsx 复制代码
"use client"
import { Button, Form, Switch } from "antd"
import { Model } from "react-vmodel"

  type FieldType = { status: number }
  const initialValues = { status: 1 }
  
export default function Demo() {
  const handleSubmit = (value: FieldType) => {
    console.log("value", value)
  }
  return (
    <Form onFinish={handleSubmit} initialValues={initialValues}>
      <Form.Item name={"status"}>
        <Model>{(vModel) => 
        <Switch {...vModel.checked({ trueValue: 1, falseValue: 0 })}></Switch>}
        </Model>
      </Form.Item>
      <Form.Item label={null}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  )
}

支持一下

热情地欢迎各位兄弟姐妹的大力支持!

github: github.com/leafio?tab=...

期待至少一个项目能达成1000个star

期待至少一个npm能达成每周1000次下载

相关推荐
香蕉可乐荷包蛋5 分钟前
vue对axios的封装和使用
前端·javascript·vue.js·axios
娃哈哈哈哈呀8 分钟前
html - <mark>标签
前端·html
QQ_hoverer8 分钟前
前端使用 preview 插件预览docx文件
前端·javascript·layui·jquery
陈随易11 分钟前
Lodash 杀手来了!es-toolkit v1.39.0 已完全兼容4年未更新的 Lodash
前端·后端·程序员
Thomas游戏开发17 分钟前
Unity3D TextMeshPro终极使用指南
前端·unity3d·游戏开发
potender18 分钟前
前端基础学习html+css+js
前端·css·学习·html·js
Hilaku27 分钟前
你以为的 Tailwind 并不高效,看看这些使用误区
前端·css·前端框架
帅夫帅夫29 分钟前
Vibe Coding从零开始教你打造一个WebLLM页面
前端·人工智能
Vonalien29 分钟前
Trae 深度体验:从怀疑到真香,AI 如何重塑我的开发流?
前端
刘白Live30 分钟前
【html】localStorage设置和获取局部存储的值
前端