[英]How do I pass a variable/literal for a value in styled components?
I always use props as it's the basic way for managing different use cases, but I'm trying to change border color during the focus state of a styled input (is it possible to assign props to a focus state?).我总是使用道具,因为它是管理不同用例的基本方法,但我试图在样式输入的焦点状态期间更改边框颜色(是否可以将道具分配给焦点状态?)。
I'm familiar with using props but even within the styled component, I'm not able to assign to a variable.我熟悉使用道具,但即使在样式组件中,我也无法分配给变量。 i can't say
{props => props.focused ? accentCol : null}
我不能说
{props => props.focused ? accentCol : null}
{props => props.focused ? accentCol : null}
. {props => props.focused ? accentCol : null}
。 The only way I've been able to assign variables has been through inline styles.我能够分配变量的唯一方法是通过内联样式。 However, afaik there's no way to access focus state through inline styles :/
但是,afaik 无法通过内联样式访问焦点状态:/
const accentCol = `{some redux function which retrieves different colors in different scenarios`
const styledInput = styled.input`
background: #181a1a;
border: 1px solid rgba(255, 255, 255, 0.4);
&::placeholder {
}
&:focus {
outline: none !important;
border: solid 2px accentCol !important;
}
`
how do I assign border color to a variable?如何将边框颜色分配给变量?
interface IProps {
focus: string,
}
const variantsfocus = {
primary: 'solid 2px accentCol',
};
const StyledInput = styled.input<IProps>`
background: #181a1a;
border: 1px solid rgba(255, 255, 255, 0.4);
&::placeholder {
}
&:focus {
outline: none !important;
border: ${props => variantsfocus[props.focus]};
}
`
I hope this would be helpful, you have to pass the prop in the component like我希望这会有所帮助,您必须在组件中传递道具,例如
<StyledInput focus="primary" />
Following the docs explanation:按照文档说明:
const StyledInput = styled.input`
&:focus {
outline: none;
border: solid 2px ${(props) => props.focusBorder};
}
`;
function App() {
return (
<>
<StyledInput focusBorder="red" />
<StyledInput focusBorder="blue" />
</>
);
}
https://codesandbox.io/s/styled-focus-etf4pd https://codesandbox.io/s/styled-focus-etf4pd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.