Aar*_*dam 10 styled-components
我正在使用https://github.com/styled-components/styled-components.
我正在尝试为需要的组件制定最佳策略@font-face.我想确保每个组件都独立于它的上下文,所以我在每个组件上定义font-family样式.但是如果我injectGlobal在多个组件中使用,我会得到@font-face相同字体的多个规则.
我应该只@font-face在ThemeProvider入口点组件中定义规则,并考虑到浏览器可能无法加载所需的字体这一事实?
mxs*_*tbr 21
这正是我们制作的原因injectGlobal.如果您看一下我们的文档,他们会说:
我们不鼓励使用它.每个应用最多使用一次,包含在一个文件中.这是逃生舱.仅用于罕见的
@font-face定义或身体造型.
所以我要做的是创建一个global-styles.js包含以下代码的JS文件:
// global-styles.js
import { injectGlobal } from 'styled-components';
injectGlobal`
@font-face {
font-family: 'My custom family';
src: url('my-source.ttf');
}
`
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我们在这里所做的只是注入一些全局样式 - 在这种情况下@font-face.完成这项工作所需的最后一件事是在主入口点导入此文件:
// index.js
import './global-styles.js'
// More stuff here like ReactDOM.render(...)
Run Code Online (Sandbox Code Playgroud)
这意味着你的font-face只注入一次,但你的所有组件仍可以访问它font-family: 'My custom family'!
这样做会给你一个不可见的文本(FOIT),但这与styled-components你无关 - 如果你使用的是vanilla CSS ,它会是一样的.要摆脱FOIT需要更高级的字体加载策略而不仅仅是@font-face.
由于这与此无关styled-components,我强烈建议您观看这两个前端中心剧集,以了解有关如何做到这一点的更多信息:"制作Web字体后备"和"西方最快的Webfont Loader"!
Ali*_*ein 10
insertGlobal已弃用。使用创建全局样式
import { createGlobalStyle } from 'styled-components'
export const GlobalStyle = createGlobalStyle`
body {
font-family: 'Muli', sans-serif;
h1 {
font-weight: 800;
font-size: 36px;
p {
font-size: 18px;
}
}
`;
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的 App.js 中使用它:
import { GlobalStyle } from './styles/global'
class App extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<>
<GlobalStyle/>
<Container/>
</>
</ThemeProvider>
)
}
}
Run Code Online (Sandbox Code Playgroud)