使用自定义控件让表格中的数字显示进度条

展示效果:

适用组件:

表格、表单、级联表等支持自定义控件的组件

操作步骤:

1.新建控件

2.提供控件中index.tsx的代码如下,并保存:

import type { Jit } from 'jit';
import type { FC } from 'react';
import { getRuntimeApp } from 'jit';
import { Progress, theme } from 'antd';
import { useState, useEffect, useMemo } from 'react';
import { ElementRender } from 'jit-widgets';

export const Render: FC<{
    props: {
        fieldConfig: any;

        data: InstanceType<typeof Jit.BaseDataType>;

        onChange?: (v: string) => void;
    };
}> = ({ props: p }) => {
    const [value, setValue] = useState(p.data.value);

    const { token } = theme.useToken();

    useEffect(() => {
        const app = getRuntimeApp();

        const handleId = p.data.onValueChange(() => {
            setValue(p.data.value);
        });

        return () => app.off(handleId);
    }, [p.data.value]);

    // 解析和验证数值

    const { numValue, isValid, progressPercent } = useMemo(() => {
        // 检查是否为有效数字
        if (isNaN(value )) {
            return {
                numValue: value ,
                isValid: false,
                progressPercent: 0,
            };
        }
        const str = String(value);
        const num = parseFloat(str);

        // 检查范围

        const isInRange = num >= 0 && num <= 1;

        const percent = isInRange ? Math.round(num * 100) : 0;

        return {
            numValue: num,

            isValid: isInRange,

            progressPercent: percent,
        };
    }, [value]);

    // 渲染逻辑

    if (!isValid) {
        return (
            <ElementRender
                value={p.data.value}
                elementPath={`datatypes.${p.fieldConfig.dataType}`}
                renderType="InlineValueRender"
                varConfig={p.fieldConfig}
            />
        );
    }

    return (
        <div
            style={{
                display: 'flex',
                flex:1,
                alignItems: 'center',
                gap: token.marginXS,
            }}
        >
            <Progress
                percent={progressPercent}
                percentPosition={{ align: 'start', type: 'inner' }}
                strokeColor={token.colorPrimary}
                size={['100%', 18]}
            />
        </div>
    );
};

3.到组件的字段中替换渲染器