我做了以下事情:
styled-components.ts - 我在 Styled-components 库的每个方法和组件中包含主题类型
import * as styledComponents from 'styled-components';
import { Theme } from './app.theme';
const {
default: styled,
css,
createGlobalStyle,
keyframes,
ThemeProvider,
} = styledComponents as styledComponents.ThemedStyledComponentsModule<Theme>;
export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;
app.tsx - 另一方面,我有一个应用程序文件,我在其中使用其中一种方法,并且除了主题 Prop 之外还想包含它自己的 Prop
mode
,是在主题中选择改变文本颜色的夜间或白天模式的变量(是一个例子)
import * as React from 'react';
import { ThemeProvider, createGlobalStyle } from './styled-components';
import styled from './styled-components';
import { theme } from './app.theme';
import { fontFaces } from './app.fonts';
type AppProps = {};
type GlobalStyleProps = {
isDarkMode: boolean;
};
const GlobalStyle = createGlobalStyle<GlobalStyleProps>`
${fontFaces}
body{
font-family: ${({ theme }): string => theme.fontFamily};
color: ${({ theme, mode }) => mode === 'dark' ? 'black' : theme.fontColor };
}
`;
export const App: React.FunctionComponent<AppProps> = () => {
const [isDarkMode, setIsDarkMode] = React.useState(false);
return (
<>
<ThemeProvider theme={theme}>
<>
<GlobalStyle mode={isDarkMode} />
<>{`Hello World!`}</>
</>
</ThemeProvider>
</>
);
};
但是我在 Lint 的 GlobalStyle 组件中得到以下错误:
Type '{ mode: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes, any, any>> & Readonly<...> & Readonly<...>'. Property 'mode' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes, any, any>> & Readonly<...> & Readonly<...>'.ts(2322)
我怎样才能解决这个问题,这样我就可以输入两个 props 而不会出现该错误?
提前致谢。
最佳答案
GlobalStyleProps
没有 mode
作为 Prop 。
如果你想使用mode
,重命名prop。
type GlobalStyleProps = {
mode: boolean, // rename from isDarkMode to mode
};
关于reactjs - 如何将类型添加到主题旁边的组件自己的 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58110830/