ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

将Javascript变量与样式组件一起使用

2019-10-04 15:35:36  阅读:222  来源: 互联网

标签:javascript styled-components


我正在使用styled-components来构建我的组件.接受自定义值的所有样式属性都会在我的组件中重复使用(应该如此).考虑到这一点,我想使用某种全局变量,以便更新将传播到所有组件,而无需单独更新每个样式.

像这样的东西:

// Variables.js

var fontSizeMedium = 16px;

// Section.js

const Section = styled.section`
  font-size: ${fontSizeMedium};
`;

// Button.js

const Button = styled.button`
  font-size: ${fontSizeMedium};
`;

// Label.js

const Label = styled.span`
  font-size: ${fontSizeMedium};
`;

我想我的语法错了但是?此外,我知道Javascript领域不推荐全局变量,但在设计中,组件之间的重用样式是绝对必要的.这里的权衡是什么?

解决方法:

包装< ThemeProvider>围绕您的应用程

https://www.styled-components.com/docs/advanced#theming

const theme = {
  fontColour: 'purple'
}

render() {
  return (
    <ThemeProvider theme={theme}>
      <MyApplication />
    </ThemeProvider>
  )
}

这将使所有子样式组件访问主题,如下所示:

const MyApplication = styled.section`
  color: ${props => props.theme.fontColour}
`

要么

const MyFancyButton = styled.button`
  background: ${props => props.theme.fontColour}
`

或通过https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components访问主题

标签:javascript,styled-components
来源: https://codeday.me/bug/20191004/1853351.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有