【问题标题】:How to use props with styled-components in switch statement如何在 switch 语句中使用带有样式组件的道具
【发布时间】:2020-12-15 16:38:46
【问题描述】:

所以我想知道是否可以在样式组件的 switch 语句中使用道具。例如,假设我有一个道具color 和一个type,即:

let HeaderCustomizations = { type: String, color: String }

还有下面的switch语句:

const headerStyle = props => {
    switch (props.type) {
        case "underline":
            return `
                padding-bottom: 2px;
                border-bottom: 3px solid rgb(134, 38, 60);
            `;
        case "borderBottom":
            return `
                width: 100%;
                // Why doesn't this work? it does not get rendered properly.
                border-bottom: 2px solid ${props => props.color};
        `;
    }
}

我是这样使用的:

export const HeaderStyling = styled('div', HeaderCustomizations)`
    display: flex;
    align-items: center;
    -webkit-box-align: center;
    margin-bottom: 0.5em;
    ${(props) => headerStyle(props)}
`;

在 switch 语句中我喜欢使用 color 属性,即:

border-bottom: 2px solid ${props => props.color};

但这似乎不起作用。我对样式组件很陌生,所以我可能会遗漏一些明显的东西......

无论如何,我很想知道如何在带有样式组件的 switch 语句中使用道具。

【问题讨论】:

    标签: reactjs vue.js styled-components


    【解决方案1】:

    它不起作用,因为您将边框颜色设置为一个函数,而不是一个值。如果你扩展 props.type 为borderBottom 的情况,你会得到:

    export const HeaderStyling = styled('div', HeaderCustomizations)`
        display: flex;
        align-items: center;
        -webkit-box-align: center;
        margin-bottom: 0.5em;
        ${(props) => `
            width: 100%;
            border-bottom: 2px solid ${props => props.color};
        `}
    `;
    

    解决办法就是把border-bottom: 2px solid ${props => props.color};改成border-bottom: 2px solid ${props.color};

    【讨论】:

    • 嗯,这很简单。干杯队友:)
    猜你喜欢
    • 2022-06-17
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多