【发布时间】:2021-04-06 18:00:49
【问题描述】:
我正在与 typescript 编译器作斗争,试图在导出的组件中期待 props,该组件呈现为 React Router 页面。 (我用的是最新版react-router-dom,5.2.0。
在我的库代码中:
interface AppProps {
baseApiUrl?: string
}
export function App({
baseApiUrl = ''
}: AppProps): React.ReactElement<AppProps> { /* my component code */ }
在我看到打字稿错误的实现代码中:
export function Sandbox(): React.ReactElement {
return (
<BrowserRouter>
<Switch>
<Route path="*">
<App baseApiUrl="http://localhost:3000" />
</Route>
</Switch>
</BrowserRouter>
)
}
为什么我会收到此打字稿错误?
TS2322: Type '{ baseApiUrl: string; }' is not assignable to type 'IntrinsicAttributes & AppProps'.
Property 'baseApiUrl' does not exist on type 'IntrinsicAttributes & AppProps'.
8 | <Switch>
9 | <Route path="*">
> 10 | <App baseApiUrl="http://localhost:3000" />
| ^^^^^^^^^^
11 | </Route>
12 | </Switch>
13 | </BrowserRouter>
这个 IntrinsicAttributes 是从哪里来的?我该怎么做才能让编译器满意?
我已经尝试过像这样重写函数签名:
export const App: React.FC<AppProps> = (props) => { /* my component code */ }
并得到相同的编译器错误。
【问题讨论】:
-
为什么不在
render或component属性上渲染App,所以history作为属性传递(通过路由属性),或者使用useHistoryReact 钩子来访问@ 987654331@ 来自路由上下文? -
这是个好建议。我编辑掉了任何
history传递并改用useHistory,不幸的是编译器仍然不喜欢它。我编辑了帖子以反映这些变化。
标签: reactjs typescript react-router tsc