【问题标题】:styled-components strongly typed [theme] propertystyled-components 强类型 [theme] 属性
【发布时间】:2018-08-17 07:28:04
【问题描述】:

我的组件使用styled-components TypeScript 和ThemeProvider,我有几个问题:

    1234563在上面设置key。我只是想知道这样做会伤害吗?或者我应该找到一种方法来创建一个ThemeProvider
  1. 由于我使用的是 TypeScript,如果我能以某种方式使我的 props.theme 属性成为强类型,那就太好了。现在,当我将鼠标悬停在props.theme 上时,我看到类型是any。如果我能以某种方式定义 theme 属性的类型而不更改 props 的推断类型,那将非常好

我现在遇到的问题是,当我为在 styled 组件中使用的 props 定义自定义 interface 时,我失去了组件推断的默认属性。例如,如果我想要这样的东西:

interface ComponentProps {
  status: string;
}

然后,我创建一个这样的组件:

const MyComp = styled.div`
  background-color: ${(props: ComponentProps) => props.theme...};
`

然后,TypeScript 会抱怨theme 不存在于ComponentProps,但是如果我没有为props 定义类型,那么当我想创建我的自定义组件时:

<MyComp status="hello" />

现在,TypeScript 抱怨属性 status 不适用于 MyComp

如果有任何帮助,我将不胜感激

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    您可以创建一个容器,并传递您喜欢的任何属性。像这样:

    styledWithProps.ts 文件中:

    import { ThemedStyledFunction } from 'styled-components';
    
    export const styledWithProps = <U>() =>
        <P, T, O>(
            fn: ThemedStyledFunction<P, T, O>
        ): ThemedStyledFunction<P & U, T, O & U> => fn;

    使用时:

    import styled, { css } from "styled-components";
    import { styledWithProps } from "./styledWithProps.ts";
    
    const MyComp = styledWithProps<any>()(styled.div) `
    ${props => props.theme==="dark" && css`
        background-color: black;
    `}
    `;
    
    const app = props => <MyComp theme="dark">{props.children}</MyComp>

    更多详情,请看这个帖子:https://github.com/styled-components/styled-components/issues/630

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 2018-02-09
      • 2021-10-25
      • 2018-03-14
      • 2020-04-27
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      相关资源
      最近更新 更多