如何限制React组件的子元素为自定义FormPage类型?
需求与实现场景
我有一个可复用的Form组件,它能接收多个FormPage类型的子元素,且该组件会在多处复用,无法预知具体使用的组件。
当前Form组件的实现代码如下:
export const Form = (props: FormProps) => { const { children } = props; const formState = useFormContainer(props); const HeaderComponent = Children.toArray(children).find( (child: FormPageType) => child.type.type === 'FormHeader' ) || <Header />; const StepsComponent = Children.toArray(children).find( (child: FormPageType) => child.type.type === 'StepsSection' ) || <StepsSection />; const filteredChildren = Children.toArray(children).filter( (child: FormPageType) => !['FormHeader', 'StepsSection'].includes(child.type.type) ); return ( <FormContext.Provider value={formState}> <div className={classes.formContainer}> {HeaderComponent} {StepsComponent} <div className={classes.pages}> {React.Children.map(filteredChildren, (child, index) => ( <SliderPage index={index}>{child}</SliderPage> ))} </div> </div> </FormContext.Provider> ); };
FormPage类型的组件需按如下方式定义:
const MyComponent: FormPage = () => {} MyComponent.formConfig = { // 一些配置项 } // 或者 MyComponent.type = 'FormHeader';
我需要在遍历Form组件的子元素时访问其formConfig属性,该属性将用于useFormContainer钩子设置步骤,同时还要过滤掉特定类型的预步骤页面组件。
采用这种设计的原因是:希望FormPage组件自行完成配置,而非依赖父组件。这样新增页面时,只需添加对应的子组件,无需修改父组件代码。
内容的提问来源于stack exchange,提问作者WitaloBenicio
相关产品推荐
相关产品推荐

