如何在使用ThemeProvider props时访问global.js中的造型-部件
例如,在theme.js中,${props => props.theme.fonts.fontSize}调用默认字体大小为16px
const theme = {
fonts: {
fontSize : '16px',
}
}
export default theme这是在/layouts/index.js中提供的
import React from 'react'
import { ThemeProvider } from 'styled-components'
import '../style/global';
import theme from '../style/theme'
class Template extends React.Component {
render() {
const { children } = this.props
return (
<ThemeProvider theme={theme}>
...
{children()}
...
</ThemeProvider>
)
}
}
export default Template从这里开始,我可以访问每个组件或子页面中的${props => props.theme.fonts.fontSize}。
但是,在全球在技术上高于theme.js的情况下,我如何以同样的方式传递给theme.js?这样我就可以创建一个全局样式
injectGlobal`
html {
font-size: (${props => props.theme.fonts.fontSize} / 16px) * 1em;
}
`发布于 2018-05-28 06:47:19
解决这一问题的最简单方法是创建一个顶级组件,该组件将您想要的样式注入如下所示:
import { Children } from 'react';
import { withTheme, injectGlobal } from 'styled-components';
const GlobalComponent = ({ theme, children }) => {
injectGlobal`
font-size: ${theme.fonts.fontSize}
}
`;
return Children.only(children);
};
export default withTheme(Global);这将确保所有将此组件作为父组件的组件都具有所需的globalStyling。希望这能帮上忙
发布于 2021-03-11 13:36:28
现在,我们可以创建一个全局组件,并将其作为ThemeProvider的子组件传递。它将允许您访问当前theme的所有支持。
应用字体系列的示例:
你的Global.js / Global.ts
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
html,
body {
padding: 0;
margin: 0;
font-family: ${(props) => props.theme.font.family}
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
`;
export default GlobalStyle;您的主要组件app.tsx / app.jsx
import theme...
import { ThemeProvider } ...
imort GlobalStyle from '../path-to-global-file';
const App ...
.
.
return(
<>
<ThemeProvider theme={theme}>
<GlobalStyle />
{ /* Root component */ }
<Component/>
</ThemeProvider>
</>
);你现在可以很容易地使用道具了。
https://stackoverflow.com/questions/50560238
复制相似问题