簡體   English   中英

TypeScript + React:如何鍵入一個“rest”道具,將道具的 rest 收集到 object 中,然后將它們傳播到某個元素?

[英]TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later spread them to some element?

function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
}) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}

export default function App() {
  return (
    <div className="App">
      <Foo style={{ background: "blue" }}>Hello CodeSandbox</Foo>
    </div>
  );
}

這是演示: https://codesandbox.io/s/how-to-type-rest-huv2z?file=/src/App.tsx:50-412

Foo用於覆蓋span接受的道具。 如何在Foo中鍵入rest

您不能直接鍵入 object 的展開部分,但可以使用聯合類型 ( & ) 添加必要的屬性。

在這種情況下,您想要允許的額外屬性是React.HTMLAttributes<HTMLSpanElement>類型。 所以你最終得到:

function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
} & React.HTMLAttributes<HTMLSpanElement>) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}

順便說一句,您可以避免使用React.FunctionComponent類型手動鍵入children屬性。 這實際上避免了聯合定義,並且在 React 代碼中更加慣用。

const Foo: React.FunctionComponent<React.HTMLAttributes<HTMLSpanElement>> = ({
  children,
  ...rest
}) => {
  // ...
}

您可以使用類似這樣的類型:

{
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
} & HTMLProps<HTMLSpanElement>

您可以只使用[x:string]: any; 喜歡

function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
  [rest:string]: any;
}) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}

export default function App() {
  return (
    <div className="App">
      <Foo style={{ background: "blue" }} id="example">Hello CodeSandbox</Foo>
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM