【问题标题】:Updating Pinterest Embeds in Preact App在 Preact 应用程序中更新 Pinterest 嵌入
【发布时间】:2017-08-04 16:16:28
【问题描述】:
我有一个组件需要根据应用程序的状态加载更改的 Pinterest 嵌入。 Pinterest 嵌入包含一个 <a> 标签,通过使用我的 HTML 底部的异步脚本(here),该标签在 <span> 标签内转换为复杂布局。但是,我无法弄清楚如何在使用更新的道具重新渲染时清除旧的 <span> 嵌入并重新运行脚本以渲染新的嵌入。谢谢!
我的组件:
const PinterestEmbed = ({ location, size }) => (
<div stye="text-align: center;margin: auto;">
<a
data-pin-do="embedPin"
data-pin-width={size}
href={location}>
Pin via Pinterest
</a>
</div>
);
export default PinterestEmbed;
【问题讨论】:
标签:
javascript
reactjs
single-page-application
pinterest
preact
【解决方案1】:
这里最简单的解决方案是切换到完整的组件:
export default class PinterestEmbed extends Component {
// keep a reference to the link so we can update it:
linkRef = el => {
this.link = el;
};
// never re-render using virtual dom:
shouldComponentUpdate() {
return false;
}
// instead, we'll handle location changes ourselves:
componentWillReceiveProps(nextProps) {
if (nextProps.location!==this.props.location) {
this.link.href = nextProps.location;
// do something to tell Pinterest to update (not sure how they expose it):
Pinterest.reInitialize(this.link);
}
}
render({ location, size }) {
return (
<div stye="text-align: center;margin: auto;">
<a
ref={this.linkRef}
data-pin-do="embedPin"
data-pin-width={size}
href={location}>
Pin via Pinterest
</a>
</div>
);
}
}