如何将含未知Props的ReactElement传入后续补全Props的泛型组件?
更优雅的泛型组件传参方案
你当前用React.cloneElement覆盖props的方式确实存在冗余(需要传入假的id),这里有两种更简洁直观的实现方案:
方案1:使用渲染Props(Render Prop)模式
把child属性定义为一个接收id参数的函数,直接在泛型组件内部调用该函数并传入获取到的id,完全不需要提前传入假props:
import React from 'react'; // 泛型组件定义 const GenericComponent = <T extends { id: string }>(props: { fetch: () => T; child: (props: { id: string }) => React.ReactElement; }) => { const { id } = props.fetch(); return <div>{props.child({ id })}</div>; }; // 子组件 const PassedInComponent = (props: { id: string }) => { return <div>{props.id}</div>; }; // 使用方式 <GenericComponent fetch={() => ({ id: 'test-id-123' })} child={(idProps) => <PassedInComponent {...idProps} />} />
方案2:将Children作为函数传递
这是渲染Props模式的变体,利用React的children属性作为函数,写法更符合React的惯用语法:
import React from 'react'; // 泛型组件定义 const GenericComponent = <T extends { id: string }>(props: { fetch: () => T; children: (props: { id: string }) => React.ReactElement; }) => { const { id } = props.fetch(); return <div>{props.children({ id })}</div>; }; // 使用方式 <GenericComponent fetch={() => ({ id: 'test-id-123' })}> {(idProps) => <PassedInComponent {...idProps} />} </GenericComponent>
方案优势
- 无需伪造初始
idprops,代码更简洁 - TypeScript类型检查更严格:函数参数的类型会直接约束子组件的props,避免类型不匹配
- 逻辑更直观:明确传递的是一个“待执行的渲染逻辑”,而非已创建的元素
内容的提问来源于stack exchange,提问作者user7467314
相关产品推荐
相关产品推荐

