【问题标题】:Styled components Typescript interface not defined样式化的组件 Typescript 接口未定义
【发布时间】:2019-11-29 23:06:04
【问题描述】:

我正在添加 styled-components 来响应 typescript 项目。在我声明 interface 并添加到我创建的样式组件之前,一切看起来都很好。

import styled from 'styled-components';

const Flex = styled.div`
    display: flex;
    flex-direction: ${props => props.direction};
`;

上面的工作正常。

后来,我给这个添加了这样的接口。

interface FlexProps {
    direction?: 'row' | 'column';
}

const Flex = styled.div<FlexProps>`
    display: flex;
    flex-direction: ${props => props.direction};
`;

我的页面因此错误而损坏。 Uncaught ReferenceError: FlexProps is not defined 来自浏览器控制台。

这是我的包的版本。

"styled-components": "^4.3.2",
"@types/styled-components": "^4.1.18",
"babel-loader": "^8.0.0-beta.0",
"babel-plugin-styled-components": "^1.10.6",
"typescript": "~3.2.1",

【问题讨论】:

  • 您使用的是什么 TypeScript 版本?在 2.9 之前,这种语法似乎是不正确的。
  • 您是否在浏览器中收到此错误?通常你只会在浏览器中得到 JS 错误,在编译器输出中得到 TS 错误。您的文件是否有 TS 或 TSX 结尾?
  • 我更新了我的问题,在那里添加了更多细节。这是Ts版本"typescript": "~3.2.1",我得到的错误来自浏览器控制台。
  • 如果它来自浏览器控制台,很可能意味着这个文件没有被编译。
  • 我很困惑为什么,因为在项目中我们同时有 JS 和 TS。它工作正常。即使是用 TS 编写的 React 组件仍然可以正常工作。只有样式化的组件不起作用。

标签: reactjs typescript webpack babeljs styled-components


【解决方案1】:

把div上的接口去掉,放到你的箭头函数里。

这样

const Flex = styled.div`
    display: flex;
    flex-direction: ${(props: FlexProps) => props.direction};
`;

【讨论】:

猜你喜欢
  • 2019-10-27
  • 2019-06-24
  • 2022-06-23
  • 2020-11-05
  • 2021-04-01
  • 2020-09-10
  • 2021-02-23
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多