简体   繁体   中英

ReactJS changing styles via State breaks CSS

So I've been learning react.

And have been learning about states/props and dynamically changing things. As such I set the states set up on a component as such:

  constructor(props) {
    super(props);
    this.modifyStyle = this.modifyStyle.bind(this);
    this.state = {
      navigation: [
        { route: "/", title: "Home" },
        { route: "/about", title: "About Me" },
        { route: "/portfolio", title: "Portfolio" },
        { route: "/contact", title: "Contact" },
        { route: "/", title: "Services" },
      ],
      styling: "nav",
    };
  }

Notice the "Styling" state.

This is used to give the list element style as such:

render() {
return (
  <div>
    <div className="trigram">
      <p>&#x2630;</p>
    </div>
    <ul className={this.state.styling}>
      {this.state.navigation.map((items) => (
        <NavItem route={items.route} title={items.title} />
      ))}
    </ul>
  </div>
);

The css for the "Styling" state is this:

   .nav {
  width: 100%;
  float: left;
  list-style: none;
  padding: 15px;
  transition: 1s;
   }

Which produces, along with the relevant li styling the following on the webpage:

[![Screenshot of menu][1]][1]

The idea is to use the following function to change the list style to a smaller one on a "Scroll" event:

  componentDidMount() {
    document.addEventListener("scroll", this.modifyStyle, true);
  }
  modifyStyle = () => {
    this.setState({
      styling: "nav2",
    });
  };

The "nav2" style which is being assigned to the state should be identical to the main menu style but with lowered padding.

.nav2 {
  width: 100%;
  float: left;
  list-style: none;
  padding: 5px;
  transition: 1s;
}

The function is called and everything works as intended. The style is changed. Yet for some reason the updated styling breaks completely and is stuck looking like this:

[![screenshot issue][2]][2]

I have no idea why this is happening and it seems no amount of debugging the CSS will resolve the issue. The Styling will just not play game here.

I expect this is something to do with the way React handles states, but I'm not really sure. Any help would be greatly appreciated.

TIA [1]: https://i.stack.imgur.com/bK1dt.png [2]: https://i.stack.imgur.com/w7Wh2.png

Not a React Question, was CSS.

Issue resolved by generalising the "li" tag css. Not specifying it in regards to a specific class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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