Prevent scrolling using CSS on React rendered components

前端 未结 2 1113
我寻月下人不归
我寻月下人不归 2021-02-05 12:05

So I render a component via React within my html like so:

 
  
    
${appHtml}
2条回答
  •  一个人的身影
    2021-02-05 12:44

    "I have no control over toggling classes based on a click within a react component."

    Not necessarily true!

    It's good that you're thinking in a "React-ful" way and wary about modifying the DOM. The main reason you want to avoid doing DOM manipulation is because it causes conflicts between what React is trying to render and the unknown changes you might be trying to make. But in this case you're not manipulating the DOM that React is rendering, you're manipulating its parent. In that case you would be totally fine doing something like this:

    document.body.style.overflow = "hidden"
    

    Or

    document.body.classList.add("no-sroll")
    

    Or whatever works. You're totally safe because React only renders the DOM within #app and doesn't care about what happens in its parent. In fact many apps and websites use React in only a small part of the page, to render a single component or widget, instead of an entire app.

    That aside, there is an even better, more "React-ful" way to do what you want. Simply restructure your app in such a way that the scrolling container is within your React app instead of body. The structure might look something like this:

    
      
        

    Make body overflow hidden, and body and #app fill the entire screen, and you can control whether #scroll-container allows scrolling or not entirely within React.

提交回复
热议问题