Javascript 如何避免样式化组件中的${props=>;props.myProp}?
我们如何避免在中编写Javascript 如何避免样式化组件中的${props=>;props.myProp}?,javascript,reactjs,react-dom,styled-components,Javascript,Reactjs,React Dom,Styled Components,我们如何避免在中编写${props=>props.myProp} 例如,如果我们正在设置按钮的样式: const Button = styled.button` background: ${props => props.background}; color: ${props => props.color}; `; render( <div> <Button background="red"
${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>
);
但这并不像只使用${props.color}
那样清晰和简单
那么,我们如何才能做到这一点呢?您可以编写一个助手函数,该函数可以在您想要从道具中提取道具的任何地方使用:
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)};
`;
根据评论中的建议,您可能也会喜欢该软件包。您可能也会喜欢该软件包!:)
const bg = 'bgColor';
const Button = styled.button`
background: ${props(bg)};
`;