防止在React渲染组件上使用CSS滚动 [英] Prevent scrolling using CSS on React rendered components

查看:152
本文介绍了防止在React渲染组件上使用CSS滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在我的 html 中通过React渲染一个组件,如下所示:

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

 <html>
  <body>
    <div id=app>${appHtml}</div>
    <script src="/bundle.js"></script>
  </body>
</html>

在我的应用程序中,我有一个汉堡按钮, onClick 全屏显示。

Within my app I have a burger button, that onClick goes full screen.

但是,正文是可滚动的。我通常会在 body 标记中添加一个类,并将其设为 overflow:hidden 以防止这种情况发生。但是,我的react组件在 body 标记内呈现,因此我无法根据react组件中的单击来控制切换类。

However, the body is scrollable. I'd normally add a class to the body tag and make it overflow: hidden to prevent this. However, my react component is rendered within the body tag so I have no control over toggling classes based on a click within a react component.

有没有人对我如何实现我想要的东西有任何想法/建议。

Has anyone got any ideas/advice on how i'd achieve what i'm looking for.

谢谢!

推荐答案

我根据反应组件中的点击无法控制切换类。

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

不一定是真的!

你正在以React-ful方式思考并且对修改DOM持谨慎态度。您希望避免执行DOM操作的主要原因是,它会导致React尝试呈现的内容与您可能尝试进行的未知更改之间发生冲突。但是在这种情况下,你不是在操纵React正在渲染的DOM,而是在操纵它的。在这种情况下,你会完全没有这样做:

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"

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

或者无论有效。你完全安全,因为React只在 #app 中呈现DOM,而不关心其父级中发生的事情。事实上,许多应用程序和网站仅在页面的一小部分使用React,以呈现单个组件或小部件,而不是整个应用程序。

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.

除此之外,还有做一个更好,更反应的方式去做你想做的事。只需重新构建您的应用程序,使滚动容器位于您的React应用程序中,而不是 body 。结构可能如下所示:

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:

<html>
  <body>
    <div id="app">
      <div id="scroll-container">
        <!-- the rest of your app -->
      </div>
    </div>
  </body>
</html>

使正文隐藏溢出, body #app 填满整个屏幕,你可以控制 #roll-container 允许滚动或不完全在React中滚动。

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.

这篇关于防止在React渲染组件上使用CSS滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆