场景: 在实际业务中我们经常会遇到需要从页面底部弹窗(银行卡弹窗,选择职业,选择地址等)弹窗上面内容允许滚动条
遇到的问题:我们在弹窗上滚动的时候会触发body的滚动事件,需要禁止body的滚动
自己实现的时候,通常会在弹窗出现的时候给body添加overflow:hidden或者添加position:fixed, 但是页面会回到顶部或者弹窗的滚动也被禁止掉了
后来发现了body-scroll-lock第三方库专门解决了这个问题
body-scroll-lock的使用
1- 安包
yarn add body-scroll-lock
2- react中的使用范例
// 1. Import the functions import { disableBodyScroll, enableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock'; class SomeComponent extends React.Component { targetElement = null; componentDidMount() { // 2. Get a target element that you want to persist scrolling for (such as a modal/lightbox/flyout/nav). // Specifically, the target element is the one we would like to allow scroll on (NOT a parent of that element). // This is also the element to apply the CSS '-webkit-overflow-scrolling: touch;' if desired. this.targetElement = document.querySelector('#targetElementId'); } showTargetElement = () => { // ... some logic to show target element // 3. Disable body scroll disableBodyScroll(this.targetElement); }; hideTargetElement = () => { // ... some logic to hide target element // 4. Re-enable body scroll enableBodyScroll(this.targetElement); }; componentWillUnmount() { // 5. Useful if we have called disableBodyScroll for multiple target elements, // and we just want a kill-switch to undo all that. // OR useful for if the `hideTargetElement()` function got circumvented eg. visitor // clicks a link which takes him/her to a different page within the app. clearAllBodyScrollLocks(); } render() { return <div>some JSX to go here</div>; } }