如何使用Typescript将道具传递到react路由器v5中的路由? [英] How to pass props to route in react router v5 with Typescript?

查看:44
本文介绍了如何使用Typescript将道具传递到react路由器v5中的路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条看起来像这样的路线,效果很好:

<路由精确={真}路径=/"渲染={() =>{返回<主页/>}}/>

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

<路由精确={真}路径=/"渲染={() =>{返回 <Home foo="bar"/>}}/>

<块引用>

输入 '{ foo: string;}' 不可分配给类型 'IntrinsicAttributes&{ 孩子?:ReactNode;}'.类型上不存在属性foo"'内在属性 &{ 孩子?:ReactNode;}'.TS2322

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

我的 Home 组件如下所示:

type homeType = {foo: 字符串}const Home:React.FC = ({foo}: homeType) =>{返回 <p>{foo}</p>}

解决方案

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

从'react'导入React;类型 CardProps = {标题:字符串,段落:字符串}export const Card = ({title,paragraph}: CardProps) =><旁边><h2>{标题}</h2><p>{ 段落 }</p></一边>const el = <卡片标题="欢迎!"段落="到这个例子"/>

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

type HomeProps = {foo: 字符串}export const Home= ({ foo }: HomeProps) =><h2>{foo}</h2>

I have a route that looks like this, which renders just fine:

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

If I add in any prop, I get the following warning:

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

Type '{ foo: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'foo' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'. TS2322

How can I pass props to a component with Typescript and React Router?

My Home component looks like this:

type homeType = {
  foo: string
}

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

解决方案

Your home component needs to be defined with the props which will be sent to it, i.e.

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" />

So with your example i presume you have a component called Home, which should be defined as such

type HomeProps = {
  foo: string
}

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


这篇关于如何使用Typescript将道具传递到react路由器v5中的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆