仅调用现有方法
invoking only existing method
我有一个 ref,其中包含一个将 window 变成全屏的方法。但是,此方法名称会根据浏览器而变化:
const setFullscreen = () => {
if (!elRef.current) return;
elRef.current
.requestFullscreen() // webkitRequestFullScreen on Safari
.then(() => {
setIsFullscreen(document[getBrowserFullScreenElementProp()] != null);
})
.catch(() => {
setIsFullscreen(false);
});
};
如您所见,Safari 使用 webkitRequestFullscreen
,所以上面的代码在 Safari 中不起作用。
如何使代码保持正常工作 DRY
?在这里找到了类似的东西 (link),但它无助于保持干燥。
我在想:
const requestFullScreen = elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen;
requestFullScreen().then .... more
然而,这不会在两个浏览器中调用该方法。
可能您需要 bind 调用目标之前的方法:
const requestFullScreen = (elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen).bind(elRef.current);
requestFullScreen().then .... more
您还可以在末尾添加带有 || () => {}
的故障保护,以便在 requestFullscreen
和 webkitRequestFullscreen
都不存在时不会崩溃:
const requestFullScreen = (elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen || () => {}).bind(elRef.current);
requestFullScreen().then .... more
我有一个 ref,其中包含一个将 window 变成全屏的方法。但是,此方法名称会根据浏览器而变化:
const setFullscreen = () => {
if (!elRef.current) return;
elRef.current
.requestFullscreen() // webkitRequestFullScreen on Safari
.then(() => {
setIsFullscreen(document[getBrowserFullScreenElementProp()] != null);
})
.catch(() => {
setIsFullscreen(false);
});
};
如您所见,Safari 使用 webkitRequestFullscreen
,所以上面的代码在 Safari 中不起作用。
如何使代码保持正常工作 DRY
?在这里找到了类似的东西 (link),但它无助于保持干燥。
我在想:
const requestFullScreen = elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen;
requestFullScreen().then .... more
然而,这不会在两个浏览器中调用该方法。
可能您需要 bind 调用目标之前的方法:
const requestFullScreen = (elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen).bind(elRef.current);
requestFullScreen().then .... more
您还可以在末尾添加带有 || () => {}
的故障保护,以便在 requestFullscreen
和 webkitRequestFullscreen
都不存在时不会崩溃:
const requestFullScreen = (elRef.current.requestFullscreen || elRef.current.webkitRequestFullscreen || () => {}).bind(elRef.current);
requestFullScreen().then .... more