Transform.tsx 1.41 KB
import React, { memo, useEffect, useState } from 'react';
import { Form } from 'antd';

export interface TransformProps {
    value?: any;
    children?: any;
    onChange?: any;
    transform: (str: any, options: any) => any[][];
}

const DefaultValue = memo(({ initialValue, onChange }: any) => {
    useEffect(() => {
        onChange(initialValue);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    return null;
})

const Transform = memo(({ children, value, onChange, transform }: TransformProps) => {
    const [items, setItems] = useState<any[]>([]);
    return (
        <>
            {React.cloneElement(children, {
                value,
                onChange: (val: any, options: any) => {
                    setItems(transform(val, options))
                    onChange(val, options);
                    if (children.props.onChange) {
                        children.props.onChange(val, options);
                    }
                }
            })}
            {items.map(([name, defaultValue, key]: any, index) => {
                return (
                    // eslint-disable-next-line react/no-array-index-key
                    <Form.Item key={index} hidden={true} name={name}>
                        <DefaultValue key={key || defaultValue} initialValue={defaultValue} />
                    </Form.Item>
                )
            })}
        </>
    )
})

export default Transform;