如何使用 Typescript 在不丢失任何道具的情况下键入样式组件?

fra*_*ana 3 typescript reactjs styled-components

我是样式组件的新手,我希望能够正确输入样式组件,这样当我传递道具“vs 代码”时,我可以自动检测我拥有的所有道具,而不仅仅是主题中的道具或那些道具我可以放一个接口。

正如我在其他一些答案中看到的那样,有没有办法不使用 HOC呢?是否有可能获得一个通用的道具,而不必像示例中那样在每个样式属性中定义 this ?

app.theme.ts

export const theme = {
  palette: {
    primaryColor: '#FF5018',
    secondaryColor: '#252729',
    tertiaryColor: '#1A1C1E',
    textColor: 'white',
  },
};

export type Theme = typeof theme;
Run Code Online (Sandbox Code Playgroud)

导航栏.styled.component.ts

export const NavigationBarStyled = styled.div`
  grid-area: navigation-bar-item;
  padding-left: 2rem;
  display: flex;
  align-items: center;
  color: ${({ theme }) => theme.palette.primaryColor};
  background-color: ${({ theme }) => theme.palette.primaryColor};
`;
Run Code Online (Sandbox Code Playgroud)

提前致谢,最好的

fra*_*ana 6

正如@Huy-Nguyen 所说,它可以解决,但在实践中,您会丢失样式组件的属性,或者您必须多次定义相同的属性。

所以最好的选择是 Styled-Components 网站所说的(定义主题界面):

主题.ts

export default interface ThemeInterface {
  primaryColor: string;
  primaryColorInverted: string;
}
Run Code Online (Sandbox Code Playgroud)

styled-components.ts

import * as styledComponents from "styled-components";

import ThemeInterface from "./theme";

const {
  default: styled,
  css,
  createGlobalStyle,
  keyframes,
  ThemeProvider
} = styledComponents as styledComponents.ThemedStyledComponentsModule<ThemeInterface>;

export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;
Run Code Online (Sandbox Code Playgroud)

然后,您使用它:

import styled from 'app/styled-components';

// theme is now fully typed
const Title = styled.h1`
  color: ${props => props.theme.primaryColor};
`;
Run Code Online (Sandbox Code Playgroud)

只需传递链接:https : //www.styled-components.com/docs/api#define-a-theme-interface

非常感谢大家。