[英]How to apply styles to a react component
我想实现,当你点击按钮时,“页面”组件变为活动状态,即一些 styles 被应用到它(让显示:块)。 styles如何挂在一个组件上?
export default () => {
const active=...
return (
<Button onClick={active}>Go</Button>
<Page />
)
};
您可以使用style
属性将 styles 添加到 DOM 元素。 内联样式文档
例如
return (
<Button onClick={active}>Go</Button>
<div style={{ display: "none" }}>
<Page />
</div>
)
您还可以使用 className 应用 CSS 类。
如果您想将 styles 直接应用于组件,您可以使用style
prop
<Page style={{display: isActive ? 'block' : 'none'}}>
<Button onClick={active}>Go</Button>
</Page>
虽然我建议使用className
<Page className={`${isActive ? 'page--active' : ''}`}>
<Button onClick={active}>Go</Button>
</Page>
you can create a style object as a state and then use it inside your onClick function to toggle state value and set it as style of the component:
const style = {
color: "red",
backgroundColor: "blue",
// and other active style
}
const [active, setActive] = useState({});
cont onActive = () => {
setActive(style);
}
return (
<Button style={active} onClick={onActive}> Go </Button>
)
你可以写一个 css class:
.active{
display: block;
}
然后将其应用于按钮:
onclick = () => document.querySelector('buttonId').classList.add('active');
return (
<Button id='buttonId' onClick={onActive}> Go </Button>
)
或通过裁判,如你所愿(我认为会更好)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.