You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TS中如何自动将父组件泛型传递给子组件?

在React TypeScript中自动传递父组件泛型给子组件的实现方案

可以实现自动传递父组件的泛型类型给子组件,无需手动为每个子组件指定泛型。下面提供两种常用的实现方式:


方法一:Render Props 模式

通过将父组件的children改为接收数据参数的函数,利用TypeScript的类型推断特性,让子组件自动继承父组件的泛型类型。

完整代码示例:

import { PropsWithChildren } from 'react';

interface ParentProps<T> {
  data: T;
  children: (data: T) => React.ReactNode;
}

const Parent = <T,>(props: ParentProps<T>) => {
  return <div>{props.children(props.data)}</div>;
};

interface ChildProps<T> {
  fieldName: keyof T;
}

const Child = <T,>({ fieldName }: ChildProps<T>) => {
  return <div>{fieldName}</div>;
};

const Example = () => {
  return (
    <Parent data={{ firstName: 'John' }}>
      {/* TypeScript自动通过data推断T的类型,Child无需手动指定泛型 */}
      <Child fieldName='firstName' />
      <Child fieldName='lastName' /> {/* 触发类型错误:'"lastName"'不能赋值给'"firstName"' */}
    </Parent>
  );
};

核心逻辑:父组件将携带泛型类型的data传递给children函数,TypeScript自动推断函数参数的类型,子组件的keyof T约束会基于该推断类型生效。


方法二:React Context 模式

通过创建泛型Context存储父组件的泛型类型,子组件从Context中获取类型约束,适合多层嵌套的组件场景。

完整代码示例:

import { createContext, useContext, PropsWithChildren } from 'react';

// 创建泛型Context,初始值设为unknown
const DataContext = createContext<unknown>(null);

interface ParentProps<T> extends PropsWithChildren {
  data: T;
}

const Parent = <T,>(props: ParentProps<T>) => {
  return (
    <DataContext.Provider value={props.data}>
      {props.children}
    </DataContext.Provider>
  );
};

// 子组件通过Context获取类型并约束fieldName
const Child = <T>({ fieldName }: { fieldName: keyof T }) => {
  const data = useContext(DataContext) as T;
  return <div>{fieldName}</div>;
};

const Example = () => {
  return (
    <Parent data={{ firstName: 'John' }}>
      <Child fieldName='firstName' />
      <Child fieldName='lastName' /> {/* 触发类型错误:'"lastName"'不在keyof T中 */}
    </Parent>
  );
};

核心逻辑:父组件通过Context.Provider传递泛型数据,子组件通过useContext获取该数据,TypeScript会根据Provider提供的类型自动约束子组件的fieldName参数。


内容的提问来源于stack exchange,提问作者OtpExhaustv2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:25:16