【避坑指“难”】Antd Cascader实现自定义新增功能

710 阅读1分钟

效果图如下:可以自定义在某一层实现数据新增 在这里插入图片描述

代码实现

对Cascader中的options做处理

		 <Cascader
            allowClear
            expandTrigger="hover"
            options={customerOption}
          />
const customerOption = handlecustomerOption(options);
const handlecustomerOption=(opt: any) =>{
  if (opt && opt.length) {
    opt.forEach((item: any) => {
      if (item.children && item.children.length) {
        item.fieldNames = item.value;
        item.children.forEach((child: any) => {
          let tempObj = {};
          tempObj = {
            label: (
              <span>
                <span title={child.value} className="layoutTitle">{child.label}</span>
                { child.label ?'':
              <Button
	              type="link"
	              icon={<PlusOutlined />}
	              style={{ marginTop: -5 }}>
              新增
            </Button>}
              </span>
            ),
            value: child.value,
            fieldNames: child.value,
          };
          Object.assign(child, tempObj);
        });
      }
    });
  }

option初始化JSON格式如下:

  const showoptions = [
    {
      value: 'zhejiang',
      label: 'Zhejiang',
      children: [
        {
          value: '',
          label: '',
        },
        {
          value: 'hangzhou',
          label: 'Hangzhou',
          children: [
            {
              value: 'xihu',
              label: 'West Lake',
            },
          ],
        },
      ],
    },
    {
      value: 'jiangsu',
      label: 'Jiangsu',
      children: [
        {
          value: 'nanjing',
          label: 'Nanjing',
        },
      ],
    },
  ];

{value: '',label: '',}相当于在下拉数据中占了顶部第一个位置,通过handlecustomerOption()将label替换成了button,从而实现新增的功能。