1

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

例如,如果我们正在设计一个按钮:

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>
);

在此处此处的文档中,我们需要编写类似${props => props.myProp}. 但这看起来很烦人且不必要。如果我们可以只写${props.myProp}.

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

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

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

那么,我们该怎么做呢?

4

1 回答 1

2

你可以编写一个辅助函数,可以在任何你想从 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)};
`;

正如mxstbr在评论中所建议的,您可能还喜欢styled-props包。

于 2017-06-26T21:25:55.380 回答