简体   繁体   English

我如何通过动态反应来更改类的CSS

[英]How do I change the css of classes through react dynamically

My question is regarding changing the CSS of classes through another class. 我的问题是关于通过另一个类更改类的CSS。 I'm aware that I can only change the CSS if the element we're trying to change is adjacent or a sibling of the selected element. 我知道,只有在我们尝试更改的元素与所选元素相邻或同级时,才能更改CSS。

My goal is to change the background color of the header and tabs class when the Link 'Bloody Mary' is selected but I don't know how to accomplish this. 我的目标是在选择链接“血腥玛丽”时更改页眉和选项卡类的背景颜色,但我不知道该如何完成。 I am using React and the way I thought about it was using states. 我正在使用React,而我对它的想法是使用状态。 The default would be white and when the Bloody Mary link is active, it would change the state from white to black. 默认值为白色,并且当Bloody Mary链接处于活动状态时,它将状态从白色更改为黑色。 I also plan on changing other styles like the font color but the main idea remains the same, changing the styling dynamically through react. 我还计划更改其他样式,例如字体颜色,但主要思想保持不变,即通过react来动态更改样式。

I have stripped my code to the basics so it looks cleaner. 我将代码剥离了基本知识,因此看起来更干净。 If you can offer some help it would be appreciated. 如果您可以提供一些帮助,将不胜感激。

  class Header extends React.Component {
    render () {
        return(
          <div>
            <div className='header'>         
              <li className='tabs'><NavLink className='style' 
              activeClassName='selected'>Home</NavLink></li>

              <li className='tabs'><NavLink className='style' 
              activeClassName='selected'>Team</NavLink></li>

              <div className='dropdown'>
                <div className='tabs'><NavLink className='style projectstab' 
                activeClassName='selected'>Projects</NavLink></div>
                <div className='dropdown-content'>
                  <a>
                    <p className='dropdown-li'>
                    </p>
                    <NavLink activeClassName='bloodyselected'>
                      Bloody Mary
                    </NavLink>
                  </a>
                </div>
              </div>

              <li className='tabs'><NavLink className='style' 
              activeClassName='selected'>Contact Us</NavLink></li>
            </div>
      )
    }
  }

The className and style directives accepts interpolation of a dynamic value. classNamestyle指令接受动态值的插值。 You can use this to achieve what you want. 您可以使用它来实现您想要的。

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { style: {} };
    this.bloodyMary = this.bloodyMary.bind(this);
  }

  bloodyMary() {
    this.setState({
      style: { backgroundColor: 'red' },
      class: 'someclass'
    });
  }

  render() {
    return <div style={this.state.style} className={this.state.class}>
      <a onClick={this.bloodyMary}>Bloody Mary</a>
    </div>;
  }
}

Take a look at the online demo 看看在线演示

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

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