【问题标题】:Typescript and styled-components gives error on importTypescript 和 styled-components 在导入时出错
【发布时间】:2021-12-21 20:01:17
【问题描述】:

获取一个使用 typescript 创建的 create-react-app 应用程序:

npx create-react-app myapp --template typescript
cd myapp
npm install styled-components@5.0.1

然后将 styled-components 添加到 typescript 文件 MyButton.tsx。

import React from 'react';
import styled from 'styled-components';  // <<<<< THIS LINE CAUSES ERROR

const MyButtonStyle = styled.button`
  background: #9590eb;
  border-radius: 3px;
  border: none;
  color: white;
`;

/**
 * MyButton is a wrapper around a Button component.  Props/arguments are:
 * onClick(event:object) => void
 * style: Pass style onto <button> element
 */
function MyButton(props:any) {
    return (
        <MyButtonStyle style={props.style} type="button" onClick={props.onClick}>{props.children}</MyButtonStyle>
    );
}

export default MyButton;

我得到了错误

TypeScript error in .../MyButton.tsx(2,20): Could not find a declaration file for module 'styled-components'. '.../myapp/node_modules/styled-components/dist/styled-components.cjs.js' implicitly has an 'any' type.

为了解决这个问题,我将文件重命名为 *.jsx,问题就消失了。
我只是在学习打字稿,所以我的想法是我需要安装一个打字稿库来支持styled-components,但我还没有弄清楚如何去做(还)。

搜索

在寻找解决方案时,我遇到了以下问题,但他们没有回答问题。

【问题讨论】:

  • 你安装了npm install @types/styled-components -D的类型吗?

标签: reactjs typescript


【解决方案1】:

样式化组件库不附带类型。相反,您需要从“确定类型”存储库中安装它。

npm i --save-dev @types/styled-components

【讨论】:

  • 我看到您刚刚加入 StackOverflow(以您的 1 名声望)。欢迎来到社区。感谢您的贡献。祝你好运。
猜你喜欢
  • 2017-06-17
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2020-02-16
  • 2020-03-02
  • 2018-05-22
  • 2021-11-25
相关资源
最近更新 更多