无法将 props 传递给 React Router 页面组件,TS2322
Cannot pass props to React Router page component, TS2322
我正在与打字稿编译器作斗争,试图在呈现为 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 */ }
并遇到相同的编译器错误。
回答你不需要做任何事情来让编译器满意。
正如您在 https://codesandbox.io/s/vibrant-wood-5clyq?file=/src/App.tsx the code you shared is fine, so there must be some other code broken somehow. For example you have two things both called AppProps, and the one that generates the error is different than the one you shared. Given you didn't share a minimal reproducible example 看到的那样,这只是一个猜测。
也许你可以通过分叉我上面分享的沙箱来制作一个可重现的例子?
我正在与打字稿编译器作斗争,试图在呈现为 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 */ }
并遇到相同的编译器错误。
回答你不需要做任何事情来让编译器满意。
正如您在 https://codesandbox.io/s/vibrant-wood-5clyq?file=/src/App.tsx the code you shared is fine, so there must be some other code broken somehow. For example you have two things both called AppProps, and the one that generates the error is different than the one you shared. Given you didn't share a minimal reproducible example 看到的那样,这只是一个猜测。
也许你可以通过分叉我上面分享的沙箱来制作一个可重现的例子?