首页 > 解决方案 > Typescript 和 styled-components 在导入时出错

问题描述

以使用 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,但我还没有弄清楚如何做到这一点(还)。

搜索

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

标签: reactjstypescript

解决方案


Styled Components 库不附带类型。相反,您需要从“确定类型”存储库中安装它。

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

推荐阅读