繁体   English   中英

在 React 中,使用 TypeScript,如何将道具转发给作为道具传递的组件?

[英]In React, using TypeScript, how can I forward props to component passed as prop?

我有一个 TS 问题,代码的 JS 版本可以工作,但我无法编译要编译的类型。

我试图为这个问题简化它。 希望我没有删除太多会对答案产生影响的内容。

因此,简化后,我正在尝试编写一个组件<Set> ,它将另一个组件作为道具,并将其包裹在<Set>的孩子周围。 此外,我希望传递给<Set>的所有道具都传递给作为道具传递的组件。

这是代码

import React, { ReactElement, ReactNode } from "react";

interface WtProps {
  children: ReactNode;
}

type WrapperType<WTProps extends WtProps> = (
  props: WTProps
) => ReactElement | null;

interface SetProps<P extends WtProps> {
  wrap: WrapperType<P>;
  children: ReactNode;
  [x: string]: unknown;
}
export function Set<WProps extends WtProps>(props: SetProps<WProps>) {
  const { wrap, children, ...rest } = props;

  return React.createElement(wrap, rest, children);
}

interface WrapperProps {
  children: ReactNode;
  foo: string;
}
const ChildWrapper: React.FC<WrapperProps> = ({ foo, children }) => {
  return (
    <div>
      <h1>ChildWrapper</h1>
      <p>{foo}</p>
      {children}
    </div>
  );
};

export default function App() {
  return (
    <Set<WrapperProps> wrap={ChildWrapper} foo="value">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some happen!</h2>
    </Set>
  );
}

这是一个代码框链接:https://codesandbox.io/s/musing-feynman-3euuu?file=/src/App.tsx

我尝试了很多不同的解决方案,但这就是我现在所拥有的。 我得到的错误是rest参数

  return React.createElement(wrap, rest, children);

它说

No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ [x: string]: unknown; }' is not assignable to parameter of type 'Attributes & WProps'.
      Type '{ [x: string]: unknown; }' is not assignable to type 'WProps'.
        'WProps' could be instantiated with an arbitrary type which could be unrelated to '{ [x: string]: unknown; }'.ts(2769)
index.d.ts(292, 14): The last overload is declared here.

我已经阅读了这个问题+答案如何修复 TS2322:“可以用不同的约束‘对象’子类型实例化”? 所以我想我知道为什么会出现错误,但我不知道该怎么做。

我需要更改什么才能使其编译?

编辑:我可以通过使wrap道具具有any类型来“修复”它,但我不想这样做。 我想要更严格的类型。 但无论如何,这里有any https://codesandbox.io/s/pedantic-nobel-x790n

我没有将 TS 与 react 一起使用,但在 React 方面有很多经验。

所以我想你可以试试这个:

export function Set<WProps extends WtProps>(props: SetProps<WProps>) {
  const { wrap, children, ...rest } = props;
  return (
    <>
      <wrap {...rest} />
      {children}
    </>
  );
}

我希望这会有所帮助,让我知道这是否有效!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM