[英]Bind external script click event to a component, but only once
我有一個Shop Component,它有另一個名為ShopItem的Component。 大約有十幾個ShopItems被渲染,並從API調用中獲取。
//Shop
render() {
const { classes } = this.props;
return (
<React.Fragment>
<div id='shop' className={classes.shopContainer}>
<Container className={classes.container}>
<div className={classes.root}>
<SwipeableViews index={this.state.value} onChangeIndex={this.onChange}>
{
this.props.productGroups.map((productGroup) => {
if (productGroup.product_ids.length > 0) {
return (
<TabContainer key={productGroup.id}>
<div className={classes.packages}>
{
this.props.products.map((product, index) => {
if (productGroup.product_ids.includes(product.id)) {
return (
<ShopItem
index={index}
maxProducts={this.props.products.length}
key={product.id}
product={product}
onBuyClick={this.onBuyClick}
buyingProduct={this.state.buyingProduct}
/>
);
}
})}
</div>
</TabContainer>
);
}
})}
</SwipeableViews>
</div>
</Container>
</div>
</React.Fragment>
);
// ShopItem
render() {
const { classes, product } = this.props;
return (
<React.Fragment>
<div className={classes.package}>
<h3 className={classes.packageTitle}>{product.title}</h3>
<strong>${product.price}</strong>
<div className={classes.packageDescription}>
<p>{product.description.split('\n')[0]}</p>
</div>
<button className={classes.button} data-selly-product={product.id}>
Buy
</button>
</div>
</React.Fragment>
);
}
我想嵌入這個腳本,所以當我點擊一個帶有data-selly-product
屬性的按鈕時,腳本會運行它的click事件。
我的嘗試是將它附加到App,Shop,甚至是ShopItem,並且除ShopItem之外沒有任何方法可以工作,但是使用該方法,我會在每個項目的文檔中加載一個腳本。
componentDidMount () {
const script = document.createElement("script");
script.src = "https://embed.selly.gg";
script.async = true;
document.body.appendChild(script);
}
我怎樣才能解決這個問題?
根據https://selly.gg/help/article/embed-a-product-on-a-website上的說明,你應該把<script src="https://embed.selly.gg"></script>
在public/index.html
文件中</head>
結束之前。
但是,這不會在您只打開產品的頁面中動態加載腳本。 但作為SPA,這將保證腳本加載一次,除非您完全重新加載您的網站。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.