Toggle Class in React

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

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

         


        
5条回答
  •  悲&欢浪女
    2020-12-13 18:51

    Ori Drori's comment is correct, you aren't doing this the "React Way". In React, you should ideally not be changing classes and event handlers using the DOM. Do it in the render() method of your React components; in this case that would be the sideNav and your Header. A rough example of how this would be done in your code is as follows.

    HEADER

    class Header extends React.Component {
    constructor(props){
        super(props);
    }
    
    render() {
        return (
            
    ) } showNav() { this.refs.sideNav.show(); } }

    SIDENAV

     class SideNav extends React.Component {
       constructor(props) {
         super(props);
         this.state = {
           open: false
         }
       }
    
       render() {
         if (this.state.open) {
           return ( 
             
    This is a sidenav
    ) } else { return null; } } show() { this.setState({ open: true }) } }

    You can see here that we are not toggling classes but using the state of the components to render the SideNav. This way, or similar is the whole premise of using react. If you are using bootstrap, there is a library which integrates bootstrap elements with the react way of doing things, allowing you to use the same elements but set state on them instead of directly manipulating the DOM. It can be found here - https://react-bootstrap.github.io/

    Hope this helps, and enjoy using React!

提交回复
热议问题