我有以下使用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}
,而不会出现任何类型错误?
发布于 2021-09-24 04:31:53
为Restaurant
组件的属性声明接口,并扩展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} />}
/>
);
};
https://stackoverflow.com/questions/69303245
复制相似问题