【问题标题】:How to add styled components as properties of an object literal while using Typescript?如何在使用 Typescript 时添加样式组件作为对象文字的属性?
【发布时间】: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"
  // ]
}

问题

有没有办法让这个模式起作用?

【问题讨论】:

标签: reactjs typescript styled-components


【解决方案1】:

我认为这里最好的方法是这样的:

const LS = {
  Title_DIV: styled.div`
     //CSS
  `,
};

const MyComponent = (props) => {
      return(
        <PostCard>
          <LS.Title_DIV>
            This is the title
          </LS.Title_DIV>
        </PostCard>
      );
    };

如果你想显式定义类型和使用接口,你可以让它悬停在标签上,比如:

然后,像这样使用它:

import styled, { StyledComponentBase } from "styled-components";

interface LS_Object {
  Title_DIV: StyledComponentBase<"div", any, {}, never>;
}

const LS: LS_Object = {
  Title_DIV: styled.div`
    // SOME CSS RULES
  `,
};

const MyComponent = (props) => {
  return(
    <PostCard>
      <LS.Title_DIV>
        This is the title
      </LS.Title_DIV>
    </PostCard>
  );
};

希望对你有帮助,干杯!

【讨论】:

  • 谢谢。这可以工作。我也发现了这个,所以我让它更通用,而不是事先命名每个属性。 interface LS_Object { [key: string]: StyledComponent&lt;any,any&gt; }
猜你喜欢
  • 2019-07-15
  • 2021-07-02
  • 2022-11-02
  • 1970-01-01
  • 2021-10-23
  • 2020-09-24
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多