reactjs - 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
,但我还没有弄清楚如何做到这一点(还)。
搜索
在寻找解决方案时,我遇到了以下问题,但他们没有回答问题。
Styled-components with TypeScript - 这是一个文件命名问题(*.ts 到 *.tsx)。
解决方案
Styled Components 库不附带类型。相反,您需要从“确定类型”存储库中安装它。
npm i --save-dev @types/styled-components
推荐阅读
- networking - 如何在 Traceroute 中跟踪 ISP?
- r - 在闪亮的应用程序中将数据帧从外部函数传递到服务器
- azure - 指向 Azure 流量管理器的 Azure CDN 终结点
- javascript - Node.js 模块,函数未正确导出
- delphi - 如何防止程序在全屏触摸屏上运行时被关闭?
- firefox - 无法访问 Firefox 插件中的 urlbar
- java - 使视图覆盖android中的所有其他视图?
- javascript - 每次更新 React 中的输入或文本区域时,onChange 事件处理程序是否会重新呈现组件?
- postgresql - 在 pgAdmin 4 中使用 SQL 查询运行示例数据库时出错
- mysql - 如何根据表 2 中的更新值更新表 1