【问题标题】:How to avoid ${props => props.myProp} in styled-components?如何避免样式组件中的 ${props => props.myProp}?
【发布时间】:2017-11-29 19:47:14
【问题描述】:

我们如何避免在styled-components中写${props => props.myProp}

例如,如果我们为按钮设置样式:

const Button = styled.button`
    background: ${props => props.background};
    color: ${props => props.color};
`;

render(
    <div>
        <Button
            background="red"
            color="white"
        >
            Example 1
        </Button>

        <Button
            background="black"
            color="yellow"
        >
            Example 2
        </Button>
    </div>
);

在文档herehere 中,我们需要编写类似${props =&gt; props.myProp} 的内容。但这看起来很烦人且不必要。 如果我们可以只写${props.myProp} 会更好。

我目前的解决方法是编写如下内容:

const Button = styled.button`${props => `
    background: ${props.background};
    color: ${props.color};
`}`;

但这并不像只使用 ${props.color} 那样简单明了。

那么,我们该怎么做呢?

【问题讨论】:

    标签: javascript reactjs react-dom styled-components


    【解决方案1】:

    你可以编写一个辅助函数,可以在任何你想从 props 中提取 props 的地方使用:

    const props = name => p => p[name];
    

    然后像这样使用它:

    const Button = styled.button`
        background: ${props('bgColor')};
    `;
    

    使用props('bgColor')props.bgColor 的语法相似性几乎是尽可能接近,同时仍保持正确的行为。

    如果你想细致,你可以创建一个变量而不是直接传递一个字符串:

    const bg = 'bgColor';
    const Button = styled.button`
        background: ${props(bg)};
    `;
    

    根据 cmets 中 mxstbr 的建议,您可能还喜欢 styled-props 包。

    【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2021-03-24
    • 2014-08-02
    • 2013-05-07
    • 2014-08-07
    • 2019-06-26
    • 2019-07-09
    • 1970-01-01
    • 2018-03-14
    相关资源
    最近更新 更多