将类添加到HTML< body>用React标记? [英] Add a class to the HTML <body> tag with React?

查看:216
本文介绍了将类添加到HTML< body>用React标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的React项目中制作一个模态,该模态需要在打开模态时将一个类添加到主体,而在关闭模态时将其删除.

Im making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.

我可以通过运行一些添加/删除类的原始javascript来完成旧的jQuery方式,但这并不像正常的React哲学.

I could do this the old jQuery way by running some vanilla javascript which adds / removes a class, however this doesnt feel like the normal React philosophy.

我应该在顶层组件上使用setState来表示模态是打开还是关闭的状态?即使我这样做了,因为将其渲染到页面上的div中,它仍然是编辑body元素的副作用,因此这种额外的接线有什么好处吗?

Should I instead setState on my top level component to say weather the modal is open or closed? Even if I did this, as its rendered into the div on the page its still a side-effect to edit the body element so is there any benefit for this extra wiring?

推荐答案

TL; DR 使用document.body.classList.adddocument.body.classList.remove

TL;DR use document.body.classList.add and document.body.classList.remove

我将有两个函数来切换状态,以显示/隐藏外部组件中的模态.

I would have two functions that toggle a piece of state to show/hide the modal within your outer component.

在这些函数中,我将使用document.body.classList.adddocument.body.classList.remove方法根据模态的状态来操纵主体类,如下所示:

Inside these functions I would use the document.body.classList.add and document.body.classList.remove methods to manipulate the body class dependant on the modal's state like below:

openModal = (event) => {
  document.body.classList.add('modal-open');
  this.setState({ showModal: true });
}
hideModal = (event) => {
  document.body.classList.remove('modal-open');
  this.setState({ showModal: false });
}

这篇关于将类添加到HTML< body>用React标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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