[英]Add to Homescreen React PWA
我正在嘗試使來自https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen的代碼起作用,但我的 React 遇到了問題。
我制作了一個名為 AddToHome 的 function
// Code to handle install prompt on desktop
export const addToHome = () => {
let deferredPrompt
const addBtn = document.querySelector('.add-button')
addBtn.style.display = 'none'
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault()
// Stash the event so it can be triggered later.
deferredPrompt = e
// Update UI to notify the user they can add to home screen
addBtn.style.display = 'block'
addBtn.addEventListener('click', () => {
// hide our user interface that shows our A2HS button
addBtn.style.display = 'none'
// Show the prompt
deferredPrompt.prompt()
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt')
} else {
console.log('User dismissed the A2HS prompt')
}
deferredPrompt = null
})
})
})
}
我正在將它導入我的 JS 文件
const handleClick = () => {
addToHome()
}
並在 div 中調用它
<button
onClick={handleClick}
style={{ position: 'absolute', top: '1px', left: '1px' }}
>
Add to home
</button>
我收到一個錯誤
似乎代碼找不到類名為“add-button”的按鈕
const addBtn = document.querySelector('.add-button')
因此在下一行嘗試訪問 styles 屬性時失敗。
addBtn.style.display = 'none'
將這個 className 添加到您的按鈕。
<button
className="add-button"
onClick={handleClick}
style={{ position: 'absolute', top: '1px', left: '1px' }}
>
Add to home
</button>
話雖如此,如果可以的話,您可能應該嘗試使用 React ref 訪問底層按鈕 DOMNode,以更 React 的方式來執行此操作。
查詢選擇器無法獲得帶有 class add-button
的任何按鈕,因為您的 HTML 中沒有任何帶有該 class 的元素,因此它返回undefined
。 應該通過將 class 添加到button
元素來修復它:
<button
onClick={handleClick}
style={{ position: 'absolute', top: '1px', left: '1px' }}
className="add-button"
>
Add to home
</button>
似乎,頁面上沒有帶有 class “添加按鈕”的元素。 似乎,當您調用這部分代碼時,生成“添加按鈕”的代碼尚未呈現。 不幸的是,我沒有看到其他代碼,但我可以嘗試建議您移動這些行
const addBtn = document.querySelector('.add-button')
在 - 的里面
window.addEventListener('beforeinstallprompt', (e) => {
將默認的 styles 移動到 CSS 並刪除該行后
addBtn.style.display = 'none'
所以,你的代碼看起來像
// Code to handle install prompt on desktop
export const addToHome = () => {
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
const addBtn = document.querySelector('.add-button')
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault()
// Stash the event so it can be triggered later.
deferredPrompt = e
// Update UI to notify the user they can add to home screen
addBtn.style.display = 'block'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.