feat: FormItem支持从类的默认属性中获取表单项的name属性,以便初始化全局状态formItem

This commit is contained in:
ranqirong 2024-10-10 13:46:51 +08:00 committed by lmaomaoz
parent 351886211c
commit 6cfad22de3
2 changed files with 61 additions and 1 deletions

View File

@ -0,0 +1,58 @@
/*
* @author: ranqirong
* @date: 2024-10-10
* @description:
*/
import React from 'react';
import {wrapControl} from '../../src/renderers/wrapControl';
import {render, screen} from '@testing-library/react';
import {RootStoreContext} from '../../src/WithRootStore';
import {RendererStore} from '../../src/store/index';
import {FormItemProps} from '../../src/renderers/Item';
const renderComponent = (WrappedComponent: any, props: any) => {
const store = RendererStore.create({});
return render(
<RootStoreContext.Provider value={store}>
<WrappedComponent rootStore={{}} $schema={{}} {...props} />
</RootStoreContext.Provider>
);
};
describe('constructor', () => {
it('如果传入有defaultProps包含name属性则创建FormItemStore', () => {
const OriginComponent = (props: FormItemProps) => {
// 用于断言formItem已被注册
return <div>{props.formItem?.storeType}</div>;
};
OriginComponent.defaultProps = {
name: 'test'
};
const WrappedComponent = wrapControl(OriginComponent as any);
renderComponent(WrappedComponent, {$schema: {}});
expect(screen.getByText('FormItemStore')).toBeInTheDocument();
});
it('如果$schema中包含name属性则创建FormItemStore', () => {
const OriginComponent = (props: FormItemProps) => {
// 用于断言formItem已被注册
return <div>{props.formItem?.storeType}</div>;
};
const WrappedComponent = wrapControl(OriginComponent as any);
renderComponent(WrappedComponent, {$schema: {name: 'test'}});
expect(screen.getByText('FormItemStore')).toBeInTheDocument();
});
it('如果$schema和defaultProps中都不包含name属性则不创建FormItemStore', () => {
const OriginComponent = (props: FormItemProps) => {
// 用于断言formItem已被注册
return <div>{props.formItem?.storeType}</div>;
};
const WrappedComponent = wrapControl(OriginComponent as any);
renderComponent(WrappedComponent, {$schema: {}});
expect(screen.queryByText('FormItemStore')).not.toBeInTheDocument();
});
});

View File

@ -176,7 +176,9 @@ export function wrapControl<
this.validate = this.validate.bind(this); this.validate = this.validate.bind(this);
this.flushChange = this.flushChange.bind(this); this.flushChange = this.flushChange.bind(this);
this.renderChild = this.renderChild.bind(this); this.renderChild = this.renderChild.bind(this);
let name = this.props.$schema.name; let name =
this.props.$schema.name ||
(ComposedComponent.defaultProps as Record<string, unknown>)?.name;
// 如果 name 是表达式 // 如果 name 是表达式
// 扩充 each 用法 // 扩充 each 用法