如何使用 Typescript 在不丢失任何道具的情况下键入样式组件? [英] How to type a styled component without losing any prop with Typescript?
问题描述
我是样式组件的新手,我希望能够正确键入我的样式组件,这样当我传递道具vs 代码"时,我可以自动检测我拥有的所有道具,而不仅仅是主题中的道具或者我可以用接口放置的那些.
我在其他一些 解决方案
它可以像@Huy-Nguyen 所说的那样解决,但在实践中,您会丢失样式组件的属性,或者您必须多次定义相同的内容.
所以最好的选择就是 Styled-Components 网站所说的(定义主题界面):
<块引用>theme.ts
导出默认接口 ThemeInterface {原色:字符串;primaryColorInverted:字符串;}
<块引用>
styled-components.ts
import * as styledComponents from "styled-components";从./theme"导入主题接口;常量{默认:样式,css,创建全局样式,关键帧,主题提供者} = styledComponents as styledComponents.ThemedStyledComponentsModule;导出 { css, createGlobalStyle, keyframes, ThemeProvider };导出默认样式;
然后,您使用它:
从'app/styled-components'导入样式;//主题现在已完全输入const 标题 = styled.h1`颜色:${props =>props.theme.primaryColor};`;
只需传递链接:https://www.styled-components.com/docs/api#define-a-theme-interface
非常感谢大家.
I'm new to styled components and I'd like to be able to type my styled components correctly so that when I pass props "vs code" I can autodetect all those props I have, not just the one in the theme or the ones I could put with an interface.
Would there be any way without using a HOC for it as I've seen in some other answer? Is it possible to get a general prop to use in all without having to be defining in each property of style this as in the example?
app.theme.ts
export const theme = {
palette: {
primaryColor: '#FF5018',
secondaryColor: '#252729',
tertiaryColor: '#1A1C1E',
textColor: 'white',
},
};
export type Theme = typeof theme;
navigation-bar.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};
`;
Thanks in advance, Best
It could be solved as @Huy-Nguyen said but in practice, you lose properties on Styled Components or you have to define the same many times.
So the best option is this as the Styled-Components website says (to define a theme interface):
theme.ts
export default interface ThemeInterface {
primaryColor: string;
primaryColorInverted: string;
}
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;
And then, you use that:
import styled from 'app/styled-components';
// theme is now fully typed
const Title = styled.h1`
color: ${props => props.theme.primaryColor};
`;
Just pass the link: https://www.styled-components.com/docs/api#define-a-theme-interface
Thank you so much for all.
这篇关于如何使用 Typescript 在不丢失任何道具的情况下键入样式组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!