我有一个React应用。我的任务是通过单击按钮来实现PWA应用程序的安装。问题-beforeinstallprompt事件不会触发。同时,当我转到浏览器菜单并选择“添加到桌面”时-应用程序已安装。
如果有任何想法我将不胜感激。
代码:
import React, {useState, useEffect } from 'react';
const styles = {
width:'100px',
height:'50px',
textAlign: 'center',
position: 'absolute',
top:0,
left:0,
transform: 'translate(50%,50%)'
}
const Test = () => {
const [supportsPWA, setSupportsPWA] = useState(false);
const [promptInstall, setPromptInstall] = useState(null);
useEffect(() => {
console.log('in use')// I see in the console
const handler = e => {
console.log('in handler') // I do not see in the console
e.preventDefault();
setSupportsPWA(true);
setPromptInstall(e);
};
window.addEventListener("beforeinstallprompt", handler);
return () => window.removeEventListener("transitionend", handler);
}, []);
const onClick = e => {
alert('click')
e.preventDefault();
if (promptInstall) {
promptInstall.prompt();
}else{
return;
};
};
return (
supportsPWA && (<button style={styles} onClick={(e) => onClick(e)}>Install</button>)
)
};
export default Test;
答案 0 :(得分:0)
问题解决了!在安装提示之前我有第二个监听器