我正在使用 mercadopago 圖書館。有必要加載 mercadopago 腳本檔案并創建 MercadoPago 物件的實體。問題是,nextJS 在包含 mercadopago 檔案之前加載了主包,所以我得到了一個執行錯誤,因為物件沒有定義。
我嘗試了不同的方法,將腳本檔案加載到帶有普通標簽和 Next/Script 物件的 Head 組件中,例如:
<script src="https://sdk.mercadopago.com/js/v2" strategy="beforeInteractive"/>
不管我做什么,接下來總是在主包檔案之后加載腳本。如果我設定一個 setTimeout 來等待實體化它運行的 Mercadopago 物件,但顯然這不是一個好的選擇。解決這個問題的正確方法是什么?
uj5u.com熱心網友回復:
好的,我使用組件上可用的 onl oad 方法解決了這個問題Next/Script。我需要做的是將腳本包含移動到我自己的組件中,并在其中包含組件,添加 onl oad 道具并傳遞一個在加載后執行我的物件實體的函式。
這是我的代碼:
const onload = () => {
const controller = new Controller(props);
setController(controller);
};
const pay = () => controller.load(props.disabled);
const attrs = {onClick: pay};
if (!controller || props.disabled) attrs.disabled = true;
return(
<>
<section className="mercadopago-checkout-pro-component">
<div ref={refContainer} className="cho-container">
<button className="btn btn-secondary" {...attrs}>
Pay
</button>
</div>
</section>
<Script src="https://sdk.mercadopago.com/js/v2" onLoad={onload}/>
</>
);
uj5u.com熱心網友回復:
在_document.jsnext.js 腳本之前加載腳本,_document.js在 pages 目錄中創建以按照您喜歡的方式擴展 html 檔案。
import Document, { Html, Head, Main, NextScript } from "next/document";
export default class MyDocument extends Document {
render(){
return (
<Html>
<Head>
/*This is loads the script in head tag of your html document*/
<script src="https://sdk.mercadopago.com/js/v2" strategy="beforeInteractive"/>
</Head>
<body>
/*your script can also go here before loading next scripts*/
<Main />
<NextScript />
</body>
</Html>
)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418658.html
標籤:
