gpt4 book ai didi

javascript - 如何避免在样式组件中使用 ${props => props.myProp}?

转载 作者:行者123 更新时间:2023-11-30 15:13:43 24 4
gpt4 key购买 nike

我们如何避免在 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 => props.myProp} 的代码。但这看起来很烦人而且没有必要。如果我们可以只写 ${props.myProp} 会更好。

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

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

但这并不像仅使用 ${props.color} 那样清晰和简单。

那么,我们该怎么做呢?

最佳答案

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

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包。

关于javascript - 如何避免在样式组件中使用 ${props => props.myProp}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com