在使用typescript创建我的 React 应用程序时,我遇到了一个我还无法解决的小问题。
我的代码:
应用程序.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import * as promise from 'redux-promise';
import reducers from './reducers';
import TemplateNavTop from './components/layout/template-nav-top';
const TestComponent2 = () => {
return <h1>TestComponent</h1>;
}
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<Switch>
<Route path="/" exact component={TestComponent} />
<Route path="/checkout">
<TemplateNavTop>
<TestComponent2 />
</TemplateNavTop>
</Route>
</Switch>
</BrowserRouter>
</Provider>
, document.getElementById('root')
模板导航顶部
import * as React from 'react';
import NavTop from './nav-top/nav-top';
export default class TemplateNavTop extends React.Component<any, {}> {
render() {
return (
<div>
asd
{this.props.children}
Footer
</div>
);
}
}
问题出现在 /checkout 路由中,它抱怨以下内容:
Type '{ path: "/checkout"; children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Route> & Readonly<{ children?: ReactNode; }> & Rea...'.
Type '{ path: "/checkout"; children: Element; }' is not assignable to type 'Readonly<RouteProps>'.
Types of property 'children' are incompatible.
Type 'Element' is not assignable to type '(props: RouteComponentProps<any>) => ReactNode'.
我发现以下解决方法确实有效:
<Route path="/checkout" component={() => TemplateWithNavBar(<TestComponent2 />)} />
但我宁愿以正确的方式去做,这里有人能帮我吗?
编辑:我确实安装了@types