我是样式化组件的新手,我希望能够正确输入样式化组件,这样当我传递 Prop “vs code”时,我可以自动检测我拥有的所有 Prop ,而不仅仅是主题中的那个或那些我可以放一个接口(interface)。
正如我在其他一些 answer 中看到的那样,是否有任何方法不使用 HOC? ?是否有可能获得一个通用的 Prop 来使用,而不必像示例中那样在样式的每个属性中进行定义?
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};
`;
提前致谢,
最好的
最佳答案
正如@Huy-Nguyen 所说,它可以解决,但实际上,您会丢失样式组件的属性,或者您必须多次定义相同的属性。
因此,最好的选择是 Styled-Components 网站所说的(定义主题界面):
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;
然后,您使用它:
import styled from 'app/styled-components';
// theme is now fully typed
const Title = styled.h1`
color: ${props => props.theme.primaryColor};
`;
只需通过链接:https://www.styled-components.com/docs/api#define-a-theme-interface
非常感谢大家。
关于reactjs - 如何使用 Typescript 在不丢失任何 Prop 的情况下键入样式组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170801/