reactjs – React-router typescript类型错误
发布时间:2020-12-15 16:18:33 所属栏目:百科 来源:网络整理
导读:在使用打字稿创建我的反应应用程序时,我遇到了一个我尚未能解决的小问题. 我的代码: App.tsx import * as React from 'react';import * as ReactDOM from 'react-dom';import { Provider } from 'react-redux';import { createStore,applyMiddleware } from
在使用打字稿创建我的反应应用程序时,我遇到了一个我尚未能解决的小问题.
我的代码: App.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 解决方法
编辑和TL; DR:只需升级您的类型声明
npm install --save-dev @types/react-router 说明 这是声明文件中的错误.问题是最初预计会有孩子的类型 ((props: RouteComponentProps<any>) => React.ReactNode | React.ReactNode) 它实际上是一个返回React.ReactNode |的联合函数React.ReactNode,它折叠成一个简单的React.ReactNode. 它究竟应该是什么 ((props: RouteComponentProps<any>) => React.ReactNode) | React.ReactNode 我已经开了a pull request for you here. 我应该提一下,你可能不想依赖这种行为.我在网上找到的几乎所有例子都在使用react-router传递函数时为子节点使用了显式属性. Even the documentation itself says that it only takes a function(而不是元素或其他任何东西). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |