如何在styled-components中使用font-style和font-family。

huangapple go评论137阅读模式
英文:

How to use font-style and font-family with styled-components

问题

我已经在GlobalStyle中设置了字体样式。但是我想在一个组件中使用另一种字体样式。但以下方式似乎不起作用。

const GlobalStyle = createGlobalStyle`
  body {
    font-family: Montserrat;
    ...
  }
`;

const App = () => {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <BrowserRouter>
        ...
      </BrowserRouter>
    </ThemeProvider>
  );
};

const Text = styled.p`
  font-style: "italic";
  font-family: "Arial";
  ...
`;

结果是以下内容:

<p font-style="italic" font-family="Arial" class="sc-gtsrHT imMzcY">

但实际上字体仍然是Montserrat,样式也是正常的。如何覆盖全局样式呢?

英文:

I have set the font-family in GlobalStyle. However I want to use another font-family and additional another font-style in one component. It somehow does not work to set it like below.

const GlobalStyle = createGlobalStyle`
  body {
    font-family: Montserrat;
    ...
  }
`;

const App = () =&gt; {
  return (
    &lt;ThemeProvider theme={theme}&gt;
      &lt;GlobalStyle /&gt;
      &lt;BrowserRouter&gt;
        ...
      &lt;/BrowserRouter&gt;
    &lt;/ThemeProvider&gt;
  );
};

and

const Text = styled.p`
  font-style: &quot;italic&quot;;
  font-family: &quot;Arial&quot;;
  ...
`;

The Result is the following

&lt;p font-style=&quot;italic&quot; font-family=&quot;Arial&quot; class=&quot;sc-gtsrHT imMzcY&quot;&gt;

But actually the font is still Montserrat and the style normal.
How can I overwrite global style?

答案1

得分: 1

尝试这个。 font-style: italic;

...
const Text = styled.p`
  font-style: italic;
  font-family: "Arial";
`;

...
return (
  ...
    <Text>Hello World</Text>
  ...
)
英文:

try this. font-style: italic;

...
const Text = styled.p`
  font-style: italic;
  font-family: &quot;Arial&quot;;
`;

...
return (
  ...
    &lt;Text&gt;Hello World&lt;Text&gt;
  ...
)

答案2

得分: 0

我认为问题在于您正在使用“p”标签而不是您创建的“Text”标签,您需要使用<Text> <Text/>而不是<p> </p>

英文:

I think the problem is that you are using the "p" tag instead of the "Text" tag you created, you need to use &lt;Text&gt; &lt;Text/&gt; instead &lt;p&gt; &lt;/p&gt;.

huangapple
  • 本文由 发表于 2023年7月17日 22:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定