【发布时间】:2020-07-30 03:21:09
【问题描述】:
我正在将使用 styled-components 构建的 React 应用程序迁移到 Typescript。
在我的 UI 组件中,我通常会创建一个空对象 LS = {}; 并将 styled 组件添加为该对象的属性。
注意: LS 代表“本地样式”,我认为这是一种将文件中声明的组件与从另一个模块导入的组件直观地分开的好方法。
例如:
MyComponent.tsx
import React from "react";
import styled from "styled-components";
import PostCard from "@components/PostCard";
const LS = {};
LS.Title_DIV = styled.div`
// SOME CSS RULES
`;
const MyComponent = (props) => {
return(
<PostCard>
<LS.Title_DIV>
This is the title
</LS.Title_DIV>
</PostCard>
);
};
export default MyComponent;
虽然这在我的 JS 环境中运行良好,但在我的 TS 环境中出现错误。
我已尝试包含以下内容:
import styled, { StyledComponent } from "styled-components";
interface LS_Object {
[key: string]: StyledComponent
};
const LS: LS_Object = {}
然后Title_DIV 错误消失了,但我得到了这个新错误:
这是我的 tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"esModuleInterop": true,
// "isolatedModules": true,
"jsx": "react",
"module": "CommonJS",
// "module": "ES6",
// "moduleResolution": "Node",
// "noEmit": true,
"strictNullChecks": true,
"target": "ES5",
"paths": {
"@components/*": ["./src/components/*"],
}
},
"include": [
"src/**/*"
],
// "exclude": [
// "node_modules",
// "dist",
// "public"
// ]
}
问题
有没有办法让这个模式起作用?
【问题讨论】:
-
看起来你必须比 StyledComponent 更具体。检查此问题github.com/styled-components/styled-components/issues/…。您可以尝试添加“StyledFunction
>”而不仅仅是“StyledComponent”
标签: reactjs typescript styled-components