如何使用Typescript将props传递给react路由器v5中的路由?

IT技术 reactjs typescript react-router
2021-05-05 22:23:42

我有一个看起来像这样的路线,它呈现得很好:

<Route
  exact={true} 
  path="/"
  render={() => {
    return <Home/>
  }}
/>

如果我添加任何props,我会收到以下警告:

<Route
   exact={true} path="/"
   render={() => {
     return <Home foo="bar"/>
   }}
/>

输入 '{ foo: 字符串; }' 不可分配给类型 'IntrinsicAttributes & { children?: ReactNode; }'。属性 'foo' 不存在于类型 'IntrinsicAttributes & { children?: ReactNode; }'。TS2322

如何使用 Typescript 和 React Router 将 props 传递给组件?

我的Home组件如下所示:

type homeType = {
  foo: string
}

const Home: React.FC = ({foo}: homeType) => { 
  return <p>{foo}</p>
}
1个回答

您的 home 组件需要使用将发送给它的 props 来定义,即

import React from 'react';

type CardProps = {
  title: string,
  paragraph: string
}

export const Card = ({ title, paragraph }: CardProps) => 
<aside>
  <h2>{ title }</h2>
  <p>
    { paragraph }
  </p>
</aside>

const el = <Card title="Welcome!" paragraph="To this example" />

所以在你的例子中,我假设你有一个名为 Home 的组件,它应该被定义为

type HomeProps = {
  foo: string
}

export const Home= ({ foo }: HomeProps) => 
  <h2>{ foo }</h2>