Pat*_*atS 5 typescript reactjs
以使用 typescript 创建的 create-react-app 应用程序为例:
npx create-react-app myapp --template typescript
cd myapp
npm install styled-components@5.0.1
Run Code Online (Sandbox Code Playgroud)
然后将样式组件添加到打字稿文件 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;
Run Code Online (Sandbox Code Playgroud)
我得到了错误
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.
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我将文件重命名为 *.jsx,问题就消失了。
我刚刚学习打字稿,所以我的想法是我需要安装一个打字稿库来支持styled-components,但我还没有弄清楚如何做到这一点(还)。
在寻找解决方案时,我遇到了以下问题,但他们没有回答问题。
使用 TypeScript 的样式组件- 这是一个文件命名问题(*.ts 到 *.tsx)。
小智 10
样式化组件库不附带类型。相反,您需要从 Definely Typed 存储库安装它。
npm i --save-dev @types/styled-components
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7221 次 |
| 最近记录: |