Toggle Class in React

后端 未结 5 910
误落风尘
误落风尘 2020-12-13 18:27

I\'m using react for a project where I have a menu button.

         


        
5条回答
  •  一整个雨季
    2020-12-13 19:05

    You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.

    UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.

    constructor(props){
        super(props);
    }
    
    getInitialState(){
      return {"showHideSidenav":"hidden"};
    }
    
    render() {
        return (
            
    ) } toggleSidenav() { var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden"; this.setState({"showHideSidenav":css}); }

    Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.

    .hidden {
       display:none;
    }
    .show{
       display:block;
    }
    

提交回复
热议问题