【React】实现输入框切换

需求

类似designable-antd平台的这个切换功能:

  • 点击右边按钮,可以切换不同的输入框样式。

实现

  • 维护一个type-component的类型数组
  • 遍历数组,找到当前组件类型并渲染
  • 当切换输入框样式的时候,获取下一个组件类型并渲染。如果为最后一个组件,则重新循环为第一个组件类型并展示
  • 初始化的时候,需要根据value校验当前组件的类型,并渲染

polyInput.tsx:

javascript 复制代码
import React, { useEffect, useState, useMemo } from 'react';
import { Button, Row, Tooltip } from 'antd';
import { useField } from '@formily/react';
import { Field } from '@formily/core';

export interface IInput {
  value: any;
  onChange: (value: any) => void;
}

export interface IPolyType {
  type: string;
  icon: JSX.Element;
  component?: any;
  checker: (value: any) => boolean;
}

export type PolyTypes = IPolyType[];

export function createPolyInput(polyTypes: PolyTypes = []): React.FC<IInput> {
  return ({ value, ...props }) => {
    const [curType, setCurType] = useState(polyTypes[0]?.type);

    const field: Field = useField();

    const curTypeItem = polyTypes.filter((i) => i.type === curType)[0];

    useEffect(() => {
      // 设置默认类型
      polyTypes?.forEach(({ checker, type }) => {
        if (checker(value)) { // here
          setCurType(type);
        }
      });
    }, []);

    const getNextType = () => {
      const currentIndex = polyTypes?.findIndex(({ type }) => type === curType);
      const nextIndex = currentIndex + 1 > polyTypes?.length - 1 ? 0 : currentIndex + 1;
      return polyTypes[nextIndex];
    };

    const renderContent = useMemo(() => {
      return (
        <>
          {curTypeItem?.component && (
            <div style={{ flex: 1, marginRight: 5 }}>
              {/* @ts-ignore */}
              {React.createElement(curTypeItem?.component, {
                ...props, // here
                value,
              })}
            </div>
          )}
          <Tooltip title={curTypeItem.type}>
            <Button
              icon={curTypeItem.icon}
              onClick={() => {
                const nextType = getNextType(); // here
                if (nextType.type === curType) {
                  return;
                }
                setCurType(nextType?.type);
                field?.setValue(undefined); // 切换类型的时候,赋空值
              }}
            />
          </Tooltip>
        </>
      );
    }, [curTypeItem]);

    return <Row justify="start">{renderContent}</Row>;
  };
}

使用:

javascript 复制代码
import { FieldStringOutlined, SwitcherOutlined } from '@ant-design/icons';
import { isObject } from 'lodash';
import { Switch } from '@formily/antd';
import LanguageTextRule, { LanguageComponentType } from '../LanguageTextRule';
import { createPolyInput } from '../PolyInput';

export enum ValidatorType {
  BOOLEAN = 'boolean',
  LANGUAGE_MESSAGE = 'message',
}

export const isBoolean = (value: any) => typeof value === 'boolean';
export const isObj = (value: any) => isObject(value);

export const ValidatorTypesMap = [
  {
    type: ValidatorType.BOOLEAN,
    icon: <SwitcherOutlined />,
    component: Switch,
    checker: isBoolean,
  },
  {
    type: ValidatorType.LANGUAGE_MESSAGE,
    icon: <FieldStringOutlined />,
    component: (props: any) => {
      return (
        <LanguageTextRule
          title="Error Message"
          componentType={LanguageComponentType.TEXT}
          buttonText="+ Error Message"
          isModal
          {...props}
        />
      );
    },
    checker: isObj,
  },
];

export default createPolyInput(ValidatorTypesMap);

效果

相关推荐
星栈8 分钟前
AI 生成页面全是紫粉渐变?我用 ui-ux-pro-max-skill 重构了整个产品页
前端·weui
avi911136 分钟前
【】js不同颜色(Vue 框架)今时今日2026年学编程入门(10月1日)
前端·vue.js·vue·vue框架·前端入门·vue入门·html上传
Fluxart.ai1 小时前
商品多角度图怎么做?Flux Art 从白底图到规格图、包装图的 10 步教程
开发语言·前端·javascript
前端繁华如梦1 小时前
React + Three.js 造了一个"乙烯基娃娃"3D 角色编辑器:配方驱动、程序化生成、还能跳舞
前端
繁华若梦7591 小时前
全项目 Skills 适配:把「会写代码的 Agent」变成「会按你们规范干活的同事」
前端
江华森1 小时前
云原生从0到1:Kubernetes 工作负载实战——Deployment/Service/滚动更新/弹性伸缩
前端·后端
江华森1 小时前
《云原生从0到1:4台华为云ECS搭建Kubernetes 1.28集群实录(上)——环境与踩坑全记录》
前端·后端
codeY2 小时前
Vite 前端发布后「点击菜单没反应」?旧版本资源 404 的完整排查与修复实录
前端·前端工程化
90后的晨仔2 小时前
uni-app Vue3 状态管理 Pinia 完全指南:从概念到实战的深度解析
前端