javascript - 菜单打开时反应选择阻止滚动
问题描述
我在我的项目中使用 react-select,当菜单打开时,我无法向下滚动我尝试设置的页面,有人熟悉这个问题吗?
<Select
styles={filter.name !== "More" ? basicStyles : moreStyles}
isMulti={filter.name !== "colorType" ? true : false}
options={options}
hideSelectedOptions={false}
closeMenuOnSelect={false}
placeholder=""
value={selectedValues ? selectedValues : []}
isClearable={false}
isSearchable={false}
onChange={addSelectFilter}
components={{ MultiValueLabel: customMultiValueLabel }}
blurInputOnSelect={false}
classNamePrefix={filter.name === "More" ? "more" : "basic-drop"}
className={filter.name === "More" ? "more-select-container" : undefined}
menuIsOpen={
filter.name === "More" ? undefined : menuIsOpen ? true : undefined
}
menuShouldBlockScroll={false}
/>
解决方案
经过长时间的研究,我找到了一个解决方案,将这段代码放在你的 index.js 中,基本上它会将任何滚动和滚轮变成被动事件
export const eventListenerOptionsSupported = () => {
let supported = false;
try {
const opts = Object.defineProperty({}, "passive", {
get() {
supported = true;
},
});
window.addEventListener("test", null, opts);
window.removeEventListener("test", null, opts);
} catch (e) {}
return supported;
};
export const noop = () => {};
const defaultOptions = {
passive: true,
capture: false,
};
const supportedPassiveTypes = ["scroll", "wheel"];
const getDefaultPassiveOption = (passive, eventName) => {
if (passive !== undefined) return passive;
return supportedPassiveTypes.indexOf(eventName) === -1
? false
: defaultOptions.passive;
};
const getWritableOptions = (options) => {
const passiveDescriptor = Object.getOwnPropertyDescriptor(options, "passive");
return passiveDescriptor &&
passiveDescriptor.writable !== true &&
passiveDescriptor.set === undefined
? Object.assign({}, options)
: options;
};
const prepareSafeListener = (listener, passive) => {
if (!passive) return listener;
return function (e) {
e.preventDefault = noop;
return listener.call(this, e);
};
};
const overwriteAddEvent = (superMethod) => {
EventTarget.prototype.addEventListener = function (type, listener, options) {
const usesListenerOptions = typeof options === "object" && options !== null;
const useCapture = usesListenerOptions ? options.capture : options;
options = usesListenerOptions ? getWritableOptions(options) : {};
options.passive = getDefaultPassiveOption(options.passive, type);
options.capture =
useCapture === undefined ? defaultOptions.capture : useCapture;
listener = prepareSafeListener(listener, options.passive);
superMethod.call(this, type, listener, options);
};
};
const supportsPassive = eventListenerOptionsSupported();
if (supportsPassive) {
const addEvent = EventTarget.prototype.addEventListener;
overwriteAddEvent(addEvent);
}
推荐阅读
- c# - 在按单选按钮查看中更改结果
- python - 无法在 Django 中取消订单
- r - R:如何对数据框中的选定变量应用命令?
- scala - 放弃断言的非单位值编译器错误
- c# - 如何在没有数据库连接的情况下使用 SQL Server 类(例如 SqlCommand)来防止 SQL 注入?
- html - 在 Google API 脚本的 HTML 服务中插入 Google Drive Link 时拒绝连接错误
- android - Firebase 云消息传递不断使我的应用程序崩溃
- html - 如何使文本居中但使它们彼此对齐
- go - 如何检查时间是否包含毫秒
- jquery - 如何通过以下方式创建 JSON 结构