反应和情感:指定字体大小

时间:2019-10-08 01:04:24

标签: css reactjs emotion

我正在使用emotion在我的React应用程序中设置样式并显示复利方程。我的render()返回此:

<div css ={equation}>
  <p>
  P (1 +</p>
  <p css={fraction}>
    <span className="num">1</span>
    <span className="symbol">/</span>
    <span className="bottom">2</span>
  </p>
  )
   <sup>(nt)</sup>
</div>

我的组件之外:

const fraction = css`
    display: inline-block;
    position: relative;
    vertical-align: middle;
    letter-spacing: 0.0001em;
    text-align: center;

    .num {
      display: block;
      padding: 0;
      height: 12px;
      line-height: 12px;
    }

    .bottom {
      border-top: thin solid black;
    }

    .symbol {
      display: none;
    }
`
const equation = css`
font-size: 100%;
.p{
    font-size:large !important;
  }
`;

分数的样式正确。但是,我无法更改p元素的字体。我唯一的解决方法是将p切换为h1元素-但我不想这样做。我希望能够在我的情感CSS样式中指定字体大小。

1 个答案:

答案 0 :(得分:1)

在您的代码中,我注意到了一些问题。

  • 您正在将.p { ...传递到方程中,该方程不是类选择器,但应该是像p { ...这样的元素选择器
  • 您的反应div必须使用className才能使效果生效

以下是沙箱代码更改:https://codesandbox.io/s/emotion-xh53z?fontsize=14

只需在此处复制以供参考:

import React from "react";
import { render } from "react-dom";
import { css } from "react-emotion";

const fraction = css`
  display: inline-block;
  position: relative;
  vertical-align: middle;
  letter-spacing: 0.0001em;
  text-align: center;
  .num {
    display: block;
    padding: 0;
    height: 30px;
    line-height: 12px;
  }
  .bottom {
    border-top: thin solid black;
  }
  .symbol {
    display: none;
  }
`;

 // Notice the p inside the equation
const equation = css`
  p { 
    font-size: large !important;
  }
`;

// Rather than css={}, you should be using className={}
const App = () => (
  <div className={equation}>
    <p>
      P (1 +
      <p className={fraction}>
        <span className="num">1</span>
        <span className="symbol">/</span>
        <span className="bottom">2</span>
      </p>
      )<sup>(nt)</sup>
    </p>
  </div>
);

render(<App />, document.getElementById("root"));

我也最后移动了结束符</p>,以确保它按照inline-block的应用

更新1:

这是最新的更新版本:https://codesandbox.io/s/emotion-1tjc7

根据他们最新的blog,您应该使用:

import styled from '@emotion/styled'
import { css } from 'emotion'

代替import styled, { css } from 'react-emotion'

更新2:

如果您不能使用香草的情感,那么可以考虑使用以下方法:

import styled from "@emotion/styled";
/** @jsx jsx */
import { css, jsx } from "@emotion/core";

根据他们的documentation

css道具有2种入门方法。

  • Babel预设(不能在Create-React-App或CodeSandbox中使用)
  • JSX Pragma(这涉及将上面的内容添加到代码行中)

我更新了相同的代码和框:https://codesandbox.io/s/emotion-0z3vz