[英]Making a Higher Order Component to inter-operate react-relay and react-router with TypeScript
好吧,我的科學怪人怪物已經失控了,我只剩下那么多頭發可以拔,所以這里的任何幫助都值得贊賞。
我正在嘗試使用React,React-Router,React-Relay和Typescript進行非常基本的應用設置。 實際上,所有功能都可以正常運行,但同時卻拋出了一些我想糾正的討厭的Typescript錯誤。
因此,基本的react-router + react-relay設置模仿了此處找到的官方react-relay方法: https : //medium.com/@cpojer/relay-and-routing-36b5439bad9
不幸的是,這個翻譯成時打字稿,並使用導入的類型,定義為通過分型反應繼電器(和,我就非常不必修改導入的類型定義); Route
已定義了道具和TypeScript對象以傳遞home
並queries
道具到Route
組件。
抱歉,我的代碼只保存在這里,但是您需要它來充分理解問題。
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import * as Relay from 'react-relay';
import MainApp from './components/MainApp';
const createRelayContainer: any = function createRelayContainer (Component: new() => React.Component<any, any>, props: any): JSX.Element {
if (Relay.isContainer(Component)) {
// construct the RelayQueryConfig from the route and the router props
const { name, queries } = props.route;
const { params } = props;
return (
<Relay.RootContainer
Component={Component}
renderFetched={(data: any) : any => <Component {...props} {...data} /> }
route={{name, params, queries}}
/>
);
}
return <Component {...props} />;
};
const homeQueries: any = {
viewer: (): Relay.QLExpression => Relay.QL`
query {
viewer
}`,
};
ReactDOM.render(
<Router
history={ browserHistory }
createElement={createRelayContainer}>
<Route>
<Route
name='home'
path='/'
component={MainApp}
queries={homeQueries}
/>
</Route>
</Router>,
document.getElementById('root'));
;
就像我說的那樣,這實際上按預期運行,但問題是Route
的react-router接口沒有name
或queries
因此TypeScript會引發錯誤。
我敢肯定有兩種不同的方法可以解決這個問題,但是我不知道在這種情況下什么是最佳實踐。
(一些基本版本信息可能會有所幫助:TypeScript 1.8.10,React 15,React-Router 2.4,React-Relay 0.8)
好的,這里最簡單的答案是通過名稱空間合並將其添加到導入的react-router定義中(我不知道Typescript允許您執行此操作)。
對於那些感興趣的人,只需添加一個overrides.d.ts
(或任何您想命名的名字)並添加到RouteProps
界面中:
declare namespace ReactRouter {
interface RouteProps {
name?: string;
queries?: any;
}
}
坦白地說,可能會有更聰明的方法來完成這件事,但這是最簡單的方法並且可行。
嘆氣,我生命中的時光流逝...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.