【问题标题】:Styles not applied at child component with Emotion 11 css prop in Gatsby and Typescript project样式未在 Gatsby 和 Typescript 项目中使用 Emotion 11 css 道具应用于子组件
【发布时间】:2021-07-26 00:32:12
【问题描述】:

我正在使用 Emotion CSS prop 来设置我的 Gatsby / Typescript 应用程序的样式。

我正在使用 Gatsby 2 和 Emotion 11。

在例如我的 Header 组件我渲染了一个 Logo 组件:

/** @jsx jsx */
import { FC } from 'react';

import { jsx } from '@emotion/react';

import Logo from 'components/Logo';
import useSiteMetaData from 'hooks/useSiteMetadata';

import Styles from './Header.styles';
import { Props } from './Header.types';

const Header: FC<Props> = () => {
  const styles = Styles();
  const { title } = useSiteMetaData();

  return (
    <header css={styles.root}>
      <Logo siteTitle={title} css={styles.logo} />
    </header>
  );
};

export default Header;

但是在我的子组件的 css 属性上,我得到一个 Typescript 错误:

类型“IntrinsicAttributes &”上不存在属性“css” 道具'.ts(2322)

我在下面添加到 tsconfig.json 并解决了 linting 错误:

{
  "compilerOptions": {
    "types": ["@emotion/react/types/css-prop"],
  }
}

但不知何故,这些样式并没有从我的Header.styles.ts 中应用,所以我可以覆盖/添加我的子组件(徽标)的一些样式?

【问题讨论】:

    标签: reactjs react-props emotion


    【解决方案1】:

    css-prop docs 中有这样的例子。

    P 组件的作用类似于您的Logo 组件,而ArticleText 是您的Header

    const P = props => (
      <p
        css={{
          margin: 0,
          fontSize: 12,
          lineHeight: '1.5',
          fontFamily: 'sans-serif',
          color: 'black'
        }}
        {...props} // <- props contains the `className` prop
      />
    )
    
    const ArticleText = props => (
      <P
        css={{
          fontSize: 14,
          fontFamily: 'Georgia, serif',
          color: 'darkgray'
        }}
        {...props} // <- props contains the `className` prop
      />
    )
    

    您的意思是需要传递className 属性,请参阅相关的answer

    【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2020-08-09
    • 2019-04-13
    • 2020-05-11
    • 2019-03-21
    • 2021-01-13
    • 2019-05-20
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多