我在做一个游戏.它有一个GameResult组件:

export default function GameResult({
  scoresData,
  onPlayAgain,
  time,
  place,
}: GameResultProps) {
  return (
    <div className="c-game-result">
      <Leaderboard scoresData={scoresData} />
      <Stats time={time} place={place} />
      <PlayAgain onClick={onPlayAgain} />
    </div>
  );

以下是其子系统的props 界面:

  • 排行榜(显示有关用户分数的数据):
interface Props {
  scoresData: string[];
}
  • 统计数据(显示游戏花费的时间和发生的地点):
interface Props {
  time: string;
  place: string;
}
  • 再次播放(再次播放的按钮):
interface Props {
  onClick: React.MouseEventHandler<HTMLButtonElement>;
}

在父组件GameResult中,我有GameResultProps个由以下所有接口组成:

interface GameResultProps {
  scoresData: string[];
  onPlayAgain: React.MouseEventHandler<HTMLButtonElement>;
  time: string;
  place: string;
}

我的问题是:How can I unify all child interfaces into a single props interface for a parent (GameResult), while keeping the interfaces separate for each child?

What I tried:
  • 将props 界面从每个子元素导入到家长,然后编写如下内容:
type GameResultProps = StatsProps & LeaderboardProps & PlayAgainProps

但它是有效的,似乎完全无法维护.为了理解游戏结果应该接受哪些props ,我必须跳转到三个文件.有没有办法简化它,这样我就可以访问父级(GameResult)中的所有子级props 类型(scoresData、OnPlay、time、place)?

推荐答案

你可以用type transformation:

在您的GameResult组件中:

interface GameResultProps {
  scoresData: string[];
  onPlayAgain: React.MouseEventHandler<HTMLButtonElement>;
  time: string;
  place: string;
}

例如,在Stats中:

type PropsStats = Pick<GameResultProps, "time" | "place">;

Typescript文档:Utility Types

然而,为了保持简单,您也可以创建一个类型文件,在其中定义所有三种类型,并将它们组合成一个GameResultProps.就像你在帖子里做的那样.

Javascript相关问答推荐

Chart.js V4切换图表中的每个条,同时每个条下有不同的标签.怎么做?

浮动Div的淡出模糊效果

空的结果抓取网站与Fetch和Cheerio

如何将Cookie从服务器发送到用户浏览器

Chart.js-显示值应该在其中的引用区域

rxjs插入延迟数据

使用领域Web SDK的Vite+Vue应用程序中的Web程序集(WASM)错误

React.Development.js和未捕获的ReferenceError:未定义useState

使用getBorbingClientRect()更改绝对元素位置

在数组中查找重叠对象并仅返回那些重叠对象

将数组扩展到对象中

如何在DYGRAPS中更改鼠标事件和键盘输入

为什么我的按钮没有从&q;1更改为&q;X&q;?

一个实体一刀VS每个实体多刀S

为什么我的SoupRequest";被重置为初始值,以及如何修复它?

当S点击按钮时,我如何才能改变它的样式?

KeyboardEvent:检测到键具有打印的表示形式

JSX/React -如何在组件props 中循环遍历数组

观察子组件中的@Output事件emits 器?

我怎么才能拿到幼风登录?