简体   繁体   English

React - 通过单击更改样式组件

[英]React - Styled Component change with Click

How can I implement CSS change(colors... font-size... etc) with click without toggling?如何通过单击而不切换来实现 CSS 更改(颜色...字体大小...等)?

menu_button.addEventListener('click', ()=>{
    bar.style.visibility = 'visible';
})

like this javascript, I just implement it just one side but I could not find how to do like this.像这个 javascript,我只是在一方面实现它,但我找不到如何这样做。

All reacts examples with css changes that I show implements with state...我展示的所有具有 css 更改的示例都使用 state 实现...

visibility: ${props => props.isHidden ? 'visible' : 'hidden'};
<NavList isHidden={navClicked}></NavList>
<SubNavButton
  onClick={()=>{
    console.log(navClicked);
    setnavClicked(!navClicked);
  }}
> 
</SubNavButton>

just like this.像这样。 I just want to do it without toggle.我只想在不切换的情况下进行。

It's actually very easy.这实际上很容易。 Using your example:使用你的例子:

<NavList isHidden={navClicked}></NavList>
  <SubNavButton onClick={()=>{
    console.log(navClicked);
    setnavClicked(false); //set it one way, so state won't change when you click again.
  }}> 
</SubNavButton>

You will need to use a state variable for this, as the state of the component will change with the click of the button.您将需要为此使用 state 变量,因为组件的 state 将随着单击按钮而改变。

If you want to set the visibility of NavList in the onClick event handler of SubNavButton, then you will have to use a state variable for the style property of the NavList.如果要在 SubNavButton 的 onClick 事件处理程序中设置 NavList 的可见性,则必须为 NavList 的样式属性使用 state 变量。 so the initial value of state variable 'visibility' can be 'visible' and onClick it can be set to 'hidden'.所以 state 变量 'visibility' 的初始值可以是 'visible' 和 onClick 它可以设置为 'hidden'。

NavList can then be然后 NavList 可以是

<NavList style= {{visibility: ${this.state.visibility} }} > <NavList style= {{visibility: ${this.state.visibility} }} >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM