如何将 Sass 变量添加到 React js 中的样式组件 [英] How to add Sass variable to Styled components in react js

查看:46
本文介绍了如何将 Sass 变量添加到 React js 中的样式组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 sass 变量添加到 react js 中的样式组件,我已经通过此链接 Sass-extract-js 和我遵循了他们的程序.

但我被困在这一行

从'styled-components'导入样式;const Button = styled.button`背景颜色:${p =>p.theme.primary}//解释这一行`;

我已经创建了 var.scss 文件并包含

$black:#000000;$白色:#ffffff;$红色:#f64406;$灰色:#333333;$green:#3bbd47;

在我的渲染中

<div><h2>欢迎回来!</h2><h3>登录您的帐户</h3>

样式组件

const Content = styled.div`h1:${}//我如何在这里获得变量`;

解决方案

这可以通过在 styled-components 中使用主题来实现.您可以向 ThemeProvider 添加变量,如下所示:

const 主题 = {黑色:#000000,白色:#ffffff红色:#f64406灰色:#333333,绿色:#3bbd47}<ThemeProvider theme={theme} ><应用程序/></ThemeProvider>

然后这个对象可以在样式组件中使用

const BlackDiv = styled`颜色:${(props) =>props.theme.black}`;

有关更多信息,请查看主题

I need to add sass variable to styled components in react js ,I have go through this link Sass-extract-js and i have followed their procedure.

but i'm stuck in this line

import styled from 'styled-components';

const Button = styled.button`
background-color: ${p => p.theme.primary} //explain this line
`;

I have created var.scss file and contains

$black:#000000;
$white:#ffffff;
$red:#f64406;
$gray:#333333;
$green:#3bbd47;

In my render

<div>
  <div>
    <h2>Welcome Back!</h2>
    <h3>Login Your Account</h3>
  </div>

Styled component

const Content = styled.div`
 h1:${}//how i can get variable here
 `;

解决方案

This can be achieved by using theming in the styled-components. You can add variables to ThemeProvider as follows:

const theme = {
black:#000000,
white:#ffffff
red:#f64406
gray:#333333,
green:#3bbd47
}
<ThemeProvider theme={theme} >
    <App />
</ThemeProvider>

and then this object can be used in the styled-components

const BlackDiv = styled`
  color: ${(props) => props.theme.black}`;

For more info please check theming

这篇关于如何将 Sass 变量添加到 React js 中的样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆