reactjs - 如何将类型添加到主题旁边的组件自己的 Prop ?

标签 reactjs typescript styled-components

我做了以下事情:

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/

相关文章:

reactjs - React-Redux 中错误处理的正确方法

reactjs - 悬停在图表上时 react-chartjs-2 垂直线

javascript - 尝试通过 Angular 服务 POST 请求时出现错误请求 404

javascript - 使用 date-fns 将日期解析为 UTC 的正确方法

javascript - 清除/重置按钮上的过滤器从事件到非事件 - Angular

javascript - 使用 styled-components 设置路由器链接的样式

javascript - 有条件地渲染带有样式组件的组件

javascript - 在 react 组件中使用异步等待

javascript - React.js : Re-render component data on add

css - 如何剪切一个正方形以便我可以绘制追逐边框?