在 props 参数下添加附加属性的 RouteComponentProps 的类型应该是什么?
What should be the type of a RouteComponentProps to add additional attributes under props parameter?
我有以下组件使用 react-router-dom:
<Route path='/restaurants/:id' render={props => (
<Restaurant {...props} user={user} />
)} />
现在,在我的 Restaurant.tsx
代码中,我似乎无法弄清楚下面 props
的正确类型应该是什么:
const Restaurant = (props: RouteComponentProps<{id: string}>) => {
const a = props.match.params.id;
const b = props.user;
...
}
对于类型 RouteComponentProps<{id: string}>
,a
被赋值没有错误。但是,b
的情况并非如此:
Property 'user' does not exist on type 'RouteComponentProps<{ id: string; }, StaticContext, unknown>'
props
的类型应该是什么,以便我可以使用 props.user
获取传递给组件的额外属性 user={user}
而不会出现任何类型错误?
为 Restaurant
组件的 props 声明接口并扩展 RouteComponentProps
接口。
import React from 'react';
import { Route, RouteComponentProps } from 'react-router-dom';
interface RestaurantProps extends RouteComponentProps<{ id: string }> {
user: any;
}
const Restaurant = (props: RestaurantProps) => {
const a = props.match.params.id;
const b = props.user;
return <div>Restaurant</div>
}
const App = () => {
const user = {};
return (
<Route
path="/restaurants/:id"
render={(props) => <Restaurant {...props} user={user} />}
/>
);
};
我有以下组件使用 react-router-dom:
<Route path='/restaurants/:id' render={props => (
<Restaurant {...props} user={user} />
)} />
现在,在我的 Restaurant.tsx
代码中,我似乎无法弄清楚下面 props
的正确类型应该是什么:
const Restaurant = (props: RouteComponentProps<{id: string}>) => {
const a = props.match.params.id;
const b = props.user;
...
}
对于类型 RouteComponentProps<{id: string}>
,a
被赋值没有错误。但是,b
的情况并非如此:
Property 'user' does not exist on type 'RouteComponentProps<{ id: string; }, StaticContext, unknown>'
props
的类型应该是什么,以便我可以使用 props.user
获取传递给组件的额外属性 user={user}
而不会出现任何类型错误?
为 Restaurant
组件的 props 声明接口并扩展 RouteComponentProps
接口。
import React from 'react';
import { Route, RouteComponentProps } from 'react-router-dom';
interface RestaurantProps extends RouteComponentProps<{ id: string }> {
user: any;
}
const Restaurant = (props: RestaurantProps) => {
const a = props.match.params.id;
const b = props.user;
return <div>Restaurant</div>
}
const App = () => {
const user = {};
return (
<Route
path="/restaurants/:id"
render={(props) => <Restaurant {...props} user={user} />}
/>
);
};