【问题标题】:Typescript/React: Module has no exported member打字稿/反应:模块没有导出的成员
【发布时间】:2019-04-10 21:00:56
【问题描述】:

我正在尝试将道具类型从一个视图组件导出到另一个容器组件并将它们用作状态类型定义:

// ./Component.tsx
export type Props {
    someProp: string;
}

export const Component = (props: Props ) => {
    ...etc
}

// ./AnotherComponent.tsx
import { Component, Props as ComponentProps } from "./Component";

type Props = {}

type State = ComponentProps & {};

class AnotherComponent extends React.Component<Props, State> {
    state: State;
    ...etc
}

但是我进入了控制台:

Module '"./Component "' has no exported member 'Props'.

对我应该如何处理这件事有什么建议吗?

我也尝试过按照this 文章使用查找类型,但没有任何乐趣。

【问题讨论】:

  • Module '"./AnotherComponent "' has no exported member 'Props'.Module "./Component" has exported member 'Props'. 欢呼
  • 抱歉打错了

标签: javascript reactjs typescript


【解决方案1】:

试试这样的。基本上扩展组件道具,以包含您想要的导入。

export interface IProps extends PropsOfYouChoiceThatYouImport {
 morePropsHere
}

也不要将道具包含在状态中,这是完全错误的 IMO。做这样的事情:


interface IProps extends YourDesiredProps {
  someProp: string | null;
  // etc
}

interface IState {
  something: boolean
  // etc
}

export class ComponentName extends Component<IProps, IState> {
  // Define you state, and props here. You need to initialize the correct IState 
  // and IProps above
}

至于控制台错误,我不确定你是否可以这样做。尝试创建一个名为TypesInterfaces 的文件夹。然后导出那个。

并在两个文件中将其导入为命名或默认导出,无论您想要什么。既然你想重用它。告诉我它是否有帮助。如果您制作一个快速的 codeSandbox,我可以进一步研究它..

基本上我的建议是把它放到一个单独的文件中:

export type Props {
    someProp: string;
}

【讨论】:

  • 谢谢,但这并不能解决上述错误。另外我猜道具只能扩展另一组道具,如果我需要包含多组道具,这将是不合适的吧?
  • 你可以扩展多个。只是用逗号分隔它们。但小心点。不兼容的类型是一个令人头疼的问题。如果您发现自己处于这种情况,那么您的架构可能是错误的。让我再看看错误。也许我误解了这个问题。
  • 请再次检查我的回答。告诉我是否有帮助。
  • 谢谢,根据github.com/sw-yx/react-typescript-cheatsheet#class-components,它说“您可以导出/导入/扩展这些类型/接口以供重用。”,当然有一种方法可以重用这些类型,而不必分离成不同的类型类型定义文件?
【解决方案2】:

如果您检查 React.Component 的 React 类型 (node_modules/react/index.d.ts),则结构如下:

class Component<P, S> {...}

其中P 等于道具,S 表示状态。 你不应该混合使用 props 和 state。

要修复您的 TypeScript 错误,请将 type 更改为 interface

export interface Props {
  someProp: string;
}

【讨论】:

  • 不幸的是,将其更改为界面不起作用。
  • 很难猜出问题出在哪里,因此我建议您在codesandbox.io 中重现您的问题,这是一个很棒的前端在线编码工具。这是一个 sand box 你可以 fork 它有 Typescript 和 React。
【解决方案3】:

缺少成员导出的问题是我有一个中间索引文件,TypeScript 在导出类型时似乎无法使用它:

// ./Component/index.tsx
export { Component, Props } from "./js/Component";

当我将导入更改为使用文件的确切路径而不是尝试通过它拾取的索引文件导入它时:

// ./AnotherComponent/js/AnotherComponent.tsx
import { Props as ComponentProps} from "./Component/js/Component";

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 2020-08-09
    • 2020-02-08
    • 2017-06-13
    • 2018-11-13
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多