[英]How to call function from App.js file inside public folder in React JS
我想調用一個 function ,它在公共文件夾的 src/App.js (callMe) 中定義,
在App.js
import messaging from './firebase-init';
import './App.css';
function App () {
function callMe() {
console.log('Call me function called');
}
return (
<div className="App">
<h1>Hello World</h1>
</div>
);
}
export default App;
我還有另一個文件firebase-messaging-sw.js位於公共文件夾中,
在firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event);
event.notification.close();
event.waitUntil(clients.matchAll({
includeUncontrolled: true,
type: "window",
}).then(function (clientList) {
console.log('********* clientList: ', clientList);
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url !== '' && 'focus' in client) {
client.focus();
callMe(); // This function is defined in src/App.js
break;
}
}
}));
});
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
const initializedFirebaseApp = firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
你能幫我嗎,我應該怎么打電話 function callMe() ?
您可以嘗試使用postMessage
window.postMessage 規范
只需在 your.js 文件中發送消息
window.postMessage('someFunctionId','*')
然后在反應中,您可以為此消息添加 eventListener (最好的解決方案是在 useEffect 中,不要忘記在回調時刪除監聽器)
useEffect(()=>{
window.addEventListener("message",handlerFunc);
return ()=> window.removeEventListener("message",handlerFunc);
}
並找到您的handlerFunc
,您可以檢查消息是否與您發布的 ID 相同...
您甚至可以通過 object 字符串來為您的 function 傳遞一些參數
window.postMessage({id:'someFunctionId',data:'test'},'*');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.