【问题标题】:Styled-component, using theme variables in RenderStyled-component,在 Render 中使用主题变量
【发布时间】:2017-10-05 17:23:14
【问题描述】:

我知道我们可以像这样使用主题变量:

const Button = styled.button`    
   cursor: pointer;
   border-radius: ${props => props.theme.borderRadiusSize};
   dir: ${props => props.theme.dir}
   outline: none;               
`;

上面的工作。我需要做的不仅仅是改变风格,还有一些主题变量。 例如:

if (theme.dir === 'rtl')
   do some stuff more in render!

我尝试使用来自propstheme 对象,如下所示:

const {theme} = this.props;
if (theme.dir === 'rtl')
   do some stuff more in render!

但是theme 属性是未定义的。

我可以使用从父<ThemeProvider/> 传递的theme 对象吗?我不想使用全局状态。

【问题讨论】:

    标签: reactjs themes styled-components


    【解决方案1】:

    我找到了解决方案。 Here 是文件。

    以前我是这样做的:

    import React from 'react';
    import PropTypes from 'prop-types';
    import styled from 'styled-components';
    
    
    class Component extends React.Component {
    
      render() {
        const {
          theme
        } = this.props;
    
        console.log('Current theme: ', theme); // Gets undefined
    
        ...
    
        return (
          ...
        )
      }
    
    }
    
    export default Component;
    

    我改成这样了:

    import React from 'react';
    import PropTypes from 'prop-types';
    import styled, {withTheme} from 'styled-components';
    
    
    class Component extends React.Component {
    
      render() {
        const {
          theme
        } = this.props;
    
        console.log('Current theme: ', theme);  // Gets theme object
    
        ...
    
        return (
          ...
        )
      }
    }
    
    export default withTheme(Component);
    

    【讨论】:

    • 我误解了你最初的问题。很好的发现(Y)
    【解决方案2】:

    它看起来不像 styled-components 为您提供了一种访问主题的简单方法。看起来你可能想要使用 React context 或其他一些全局配置,如果它真的是这样的话。从 ThemeProvider 访问主题以获取样式以外的内容将访问样式组件的内部。

    【讨论】:

    • 我试图访问styled-components的内部但找不到任何有用的对象。
    • 对,我也是。似乎没有公开的或容易找到的私有 API 来执行此操作。这就是为什么我提出了不同的解决方案。如果你换个角度思考,它可能会更好。目前,您似乎在要求 CSS 样式规则来通知非 CSS 逻辑、定位等。反之,如果您尝试在上下文/全局状态中保留更通用的变量,it可以影响样式规则以及其他所有内容。 context.direction 可以决定字体方向,以及标志位置等。
    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 2020-02-13
    • 2021-07-19
    • 2021-01-29
    • 2020-10-04
    • 2020-03-09
    • 2022-10-21
    • 2019-05-11
    相关资源
    最近更新 更多