【发布时间】:2017-10-24 11:24:19
【问题描述】:
我在 React 中使用 typescript 抽象类作为我的布局组件的基类,该基类的用法如下所示:
import { IPageLayoutActions, IPageLayoutLocalState, IPageLayoutProps, PageLayoutNoSidebar } from 'pg-face/dist/layouts/PageLayoutNoSidebar';
export interface ITestPageProps extends IPageLayoutProps
{
loremIpsum: string;
}
export interface ITestPageActions extends IPageLayoutActions {}
interface ITestPageLocalState extends IPageLayoutLocalState {}
export
class TestPage
extends PageLayoutNoSidebar<ITestPageProps && ITestPageActions, ITestPageLocalState>
{
renderPageContent() {
return <span>{ this.props.loremIpsum }</span>;
}
}
PageLayoutNoSidebar 组件实际上扩展了另一个名为 PageLayout 的类,它是我的应用程序中所有布局的基类。当一切都在一个项目中时,它可以工作。
现在我想将所有这些布局文件移动到单独的 npm 模块中,以便在我的所有应用程序中重复使用(我只是在测试它,所以我从本地目录加载包)。所以我创建了一个包,使用“tsc -d -p ./”将 typecscript 代码转换为 js 和定义文件。这些文件存储在包的 dist 目录中。然后我更新了项目目录中的包。
之后,当我尝试在我的项目中使用这个类时,我得到了
error TS2339: Property 'props' does not exist on type 'TestPage'
我发现当PageLayoutNoSidebar不扩展PageLayout时(我把PageLayout中的所有代码直接复制到PageLayoutNoSidebar中),这个问题就消失了,所以估计是exports有问题。
你知道代码有什么问题吗?
这些类的代码如下所示:
PageLayout.tsx
import * as React from 'react';
import { Header, IHeaderActions, IHeaderProps } from '../blocks';
export interface IPageLayoutProps extends IHeaderProps {}
export interface IPageLayoutActions extends IHeaderActions {}
export interface IPageLayoutLocalState {
headerCollapsed: boolean;
}
export
abstract class PageLayout<P extends IPageLayoutProps & IPageLayoutActions, S extends IPageLayoutLocalState>
extends React.Component<P, S>
{
abstract render(): JSX.Element
renderPageHeader() {
return (
<Header
headerCollapsed={this.state.headerCollapsed}
mainMenuItems={this.props.mainMenuItems}
onHeaderToggle={this._toggleHeader}
/>
);
}
renderPageContent(): JSX.Element | null {
return null;
}
_toggleHeader = (headerCollapsed: boolean) => {
this.setState({
headerCollapsed
});
}
//...
}
PageLayoutNoSidebar.tsx
import * as React from 'react';
import { IPageLayoutActions, IPageLayoutLocalState, IPageLayoutProps, PageLayout } from './PageLayout';
export
class PageLayoutNoSidebar<P extends IPageLayoutProps & IPageLayoutActions, S extends IPageLayoutLocalState>
extends PageLayout<P, S>
{
render() {
return (
<div>
{this.renderPageHeader()}
<main className="container-narrow">
{this.renderPageContent()}
</main>
</div>
);
}
}
【问题讨论】:
-
你确定相对路径
import { Header, IHeaderActions, IHeaderProps } from '../blocks';吗? -
这只是一个位于包中并在布局内部使用的组件。我没有提到它,因为我想让问题尽可能简单
标签: reactjs typescript npm package webpack-2