如何避免用${props => props.myProp}编写https://www.styled-components.com/
例如,如果我们正在设计一个按钮:
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>
);在docs、这里和这里中,我们需要编写类似于${props => props.myProp}的东西。但这看起来既烦人又没有必要。如果我们只写${props.myProp}就更好了。
我目前的解决办法是编写如下内容:
const Button = styled.button`${props => `
background: ${props.background};
color: ${props.color};
`}`;但这并不像使用${props.color}那样简单明了。
那么,我们怎么做呢?
发布于 2017-06-26 21:25:55
您可以编写一个助手函数,该函数可以在任何想从道具中提取道具的地方使用:
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)};
`;https://stackoverflow.com/questions/44768711
复制相似问题