首页 > 解决方案 > React 中的样式化组件:TypeError:无法读取未定义的属性“颜色”

问题描述

我在 React 中使用样式化组件,感觉就像我从另一个运行良好的组件中剪切并粘贴了这段代码。但是,我收到此错误:

TypeError:无法读取未定义的属性“白色”

如果我只输入一种颜色,它就可以正常工作。但是如果我尝试使用我的主题,我会得到那个错误。

这是我的组件:(白色和橙色给出相同的错误)

import React, {Component} from 'react';
import {Button, Row, ThemeProvider} from 'react-bootstrap';
import styled from 'styled-components';
import theme from "../../Config/Theme";

const Div = styled.div `
    height: 100vh;
    padding: 2em;
    display: flex;
    align-items: center;
    justify-content: center;

`

const StyledButton = styled(Button) `
    margin: 0.25em;
    width: 10em;
    height: 7em;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: ${props => props.theme.colors.white};
    &:hover{
        color: ${props => props.theme.colors.orange};
    }

    div{
        margin-top: 1em;
        font-size: .75em;
    }
    

`

class Tools extends Component {


    render(){
        return(
            <ThemeProvider theme={theme}>
                <Div>
                    <StyledButton>
                        <i class="fal fa-server fa-2x"></i>
                        <div>Client Database</div>
                    </StyledButton>
                    <StyledButton href="/handbook">
                        <i class="fal fa-book fa-2x"></i>
                        <div>Handbook Creator</div>
                    </StyledButton>
                </Div>
            </ThemeProvider>
            
        )
    }
}

export default Tools;

然后这是我的主题:

export default {
    colors: {
        orange: "#ffa600",
        light_blue: "#009fc4",
        medium_blue: "#07485c",
        dark_blue: "#14141e",
        bg_trans: "rgba(255, 255, 255, 0.8)",
        bg_gray: "f4f4f4",
        black: "#000",
        white: "#fff"
    },
    sizes: {
        tiny_phone: "414px;",
        portrait_phone: "575.98px",
        landscape_phone: "768.89px;",
        tablet: "991.98px",
        desktop: "1199.98px"
    }

}

谁能看到我错过了什么?在我看来,它和其他正在工作的人一样......所以我显然只是没有看到简单的东西。在此先感谢您的帮助。

标签: reactjsreact-nativereact-bootstrapstyled-components

解决方案


当然,我在发布后立即想通了。我的错误是将 ThemeProvider 作为引导程序的一部分而不是样式组件导入。

所以这:

import React, {Component} from 'react';
import {Button, ThemeProvider} from 'react-bootstrap';
import styled from 'styled-components';
import theme from "../../Config/Theme";

需要是这样的:

import React, {Component} from 'react';
import {Button} from 'react-bootstrap';
import styled, {ThemeProvider} from 'styled-components';
import theme from "../../Config/Theme";

嗬!


推荐阅读