我使用NavLink
为styled
设置样式,由于某种原因,当组件位于我要使用的同一文件中时,它可以正常工作。如果我将其移至单独的组件文件打字稿,则会引发错误。
这是工作代码:
import * as React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom';
import styled, { ThemeProvider, theme } from '@/theme';
const store = configureStore();
const Index = () => <h2>Home</h2>;
const Help = () => <h2>Help</h2>;
const NavigationItem = styled(NavLink)`
color: green;
&[aria-current] {
color: red;
}
`;
const App = () => (
<Provider store={store}>
<ThemeProvider theme={theme}>
<Router>
<>
<Sidebar>
<NavigationItem to="/" exact>
Home
</NavigationItem>
<NavigationItem to="/Help">Help</NavigationItem>
</Sidebar>
<Content>
<Route path="/" exact component={Index} />
<Route path="/help/" component={Help} />
</Content>
</AppWrapper>
</>
</Router>
</ThemeProvider>
</Provider>
);
现在,如果我将NavigationItem
移到一个单独的文件中:
NavigationItem.ts
import { BrowserRouter as NavLink } from 'react-router-dom';
import styled from '@/theme';
const NavigationItem = styled(NavLink)`
color: green;
&[aria-current] {
color: red;
}
`;
export default NavigationItem;
和App.tsx
import * as React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import styled, { ThemeProvider, theme } from '@/theme';
const store = configureStore();
const Index = () => <h2>Home</h2>;
const Help = () => <h2>Help</h2>;
import NavigationItem from './NavigationItem';
const App = () => (
<Provider store={store}>
<ThemeProvider theme={theme}>
<Router>
<>
<Sidebar>
<NavigationItem to="/" exact>
Home
</NavigationItem>
<NavigationItem to="/help">Help</NavigationItem>
</Sidebar>
<Content>
<Route path="/" exact component={Index} />
<Route path="/help/" component={Help} />
</Content>
</AppWrapper>
</>
</Router>
</ThemeProvider>
</Provider>
);
我收到这个奇怪的错误:
Type '{ children: string; to: string; exact: true; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<BrowserRouterProps & RefAttributes<BrowserRouter>, "ref" | "basename" | "getUserConfirmation" | "forceRefresh" | "keyLength" | "key"> & Partial<...>, "ref" | ... 4 more ... | "key"> & { ...; } & { ...; } & { ...; }'.
Property 'to' does not exist on type 'IntrinsicAttributes & Pick<Pick<BrowserRouterProps & RefAttributes<BrowserRouter>, "ref" | "basename" | "getUserConfirmation" | "forceRefresh" | "keyLength" | "key"> & Partial<...>, "ref" | ... 4 more ... | "key"> & { ...; } & { ...; } & { ...; }'.
由于两种方法之间没有区别,所以我不理解错误的原因。
答案 0 :(得分:0)
在NavigationItem.ts
中,您正在使用import { BrowserRouter as NavLink } from 'react-router-dom';
但是工作代码为import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom';
import { BrowserRouter as NavLink } from 'react-router-dom';
import styled from '@/theme';
const NavigationItem = styled(NavLink)`
color: green;
&[aria-current] {
color: red;
}
`;
export default NavigationItem;