gpt4 book ai didi

reactjs - Styled-components:尝试为已经设置样式的组件设置样式时不应用样式

转载 作者:行者123 更新时间:2023-12-05 02:53:08 25 4
gpt4 key购买 nike

我正在尝试为已经设置样式的组件设置样式。但新规则中的样式不适用于输出 CSS。

我可以为已经设置样式的组件设置样式吗?

预先感谢您的帮助。

编辑:添加其余的 LanugageChooser 定义

// COMPONENT THAT I'M TRYING TO STYLE
const LanguageChooser = () => {
const Container = styled.div`
display: flex;
align-items: center;
height: 36px;
& > div:not(:last-child) {
margin-right: 5px;
}
`;

return (
<Container>
<Flag { ...languages.pl }/>
<Flag { ...languages.en }/>
</Container>
)
}

const Flag = ({ flag, language }) => {
const { i18n } = useTranslation();

const Button = styled.div`
cursor: pointer;
font-size: 24px;
transition: .2s all;
&:hover {
font-size: 36px;
}
`;

return (
<Button onClick={ () => i18n.changeLanguage(language) }>{ flag }</Button>
)
}
// TRYING ADD MARGIN LEFT, BUT THERE IS NO RESULT.
// ANY OTHER CSS PROPERTY ARE NOT APPLYING
const Navbar = ({ color }) => {
...

const StyledLanguageChooser = styled(LanguageChooser)`
margin-left: auto;
`;

const Nav = styled.nav`
display: flex;
align-content:center;
background: ${ color };
padding: 2px 3px;
`;

return (
<Nav className="navbar">
<StyledNavLink to="/home">...</StyledNavLink>
<StyledNavLink to="/maps">...</StyledNavLink>
<StyledNavLink to="/charts">...</StyledNavLink>
<StyledLanguageChooser/>
</Nav>
)
}

最佳答案

首先,将带样式的组件移动到功能范围之外,否则您的样式将在每次渲染时重置,您将遇到严重的性能问题

其次,为了应用样式,您需要传递className 属性。

参见 Styling normal React components

If you use the styled(MyComponent) notation and MyComponent does not render the passed-in className prop, then no styles will be applied.

const Container = styled.div`
display: flex;
align-items: center;
height: 36px;
& > div:not(:last-child) {
margin-right: 5px;
}
`;
const LanguageChooser = ({ className }) => {
return (
<Container className={className}>
<Flag {...languages.pl} />
<Flag {...languages.en} />
</Container>
);
};

const Button = styled.div`
cursor: pointer;
font-size: 24px;
transition: 0.2s all;
&:hover {
font-size: 36px;
}
`;

const Flag = ({ flag, language }) => {
const { i18n } = useTranslation();

return <Button onClick={() => i18n.changeLanguage(language)}>{flag}</Button>;
};

关于reactjs - Styled-components:尝试为已经设置样式的组件设置样式时不应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62300722/

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