如何解决当属性由于窗口调整大小而改变时,点亮的元素打字稿不会重新呈现
我正在基于窗口的宽度(也基于UI中存在的其他元素)显示卡片图像。触发窗口调整大小事件时,重新计算正确进行,但更新的属性未重新呈现。 为了进行测试,我添加了一个虚拟按钮,并在调整窗口大小后单击了相同的重新计算函数。但是,这会正确触发重新渲染。 在下面添加代码:
import {LitElement,html,customElement,property} from 'lit-element';
@customElement('my-component')
export class MyComponent extends LitElement {
@property({type: Number}) computednumCards: number = 0;
@property({type: Array}) dummyCards: Array<any> = [];
constructor() {
super();
this.computednumCards = 0;
this.dummyCards = [];
}
connectedCallback() {
super.connectedCallback();
this.init();
this.computeNumCards()
}
computeNumCards() {
let cardWidth = 320;
let pageWidth = window.innerWidth;
//some more computation here,simplifying as its not relevant for this question
this.computednumCards = Math.floor((pageWidth / cardWidth));
this.dummyCards = Array(this.computednumCards).fill(html`<span> <img src="card.png"/></span>`);
console.log(pageWidth);
}
init() {
let self = this;
window.onresize = function(){
setTimeout(self.computeNumCards,1000);
};
}
//on adding the dummy button below and clicking it after re-sizing the window,the cards are re-rendered properly
render() {
return html`
<div class="container">
<button id="1" @click="${() => this.computeNumCards()}" aria-label="computeCards">-</button>
<p>${this.computednumCards}</p>
${this.computednumCards && this.computednumCards > 0? this.dummyCards.map(dummyCard => {
return dummyCard
}) : html``}
</div>
`;
}
}
解决方法
触发onresize
回调时,this
内部的computeNumCards
不是Window
实例的MyComponent
。因此,您要在Window
而不是组件上设置新属性。如果您使用arrow functions,上下文将是正确的,然后将设置组件状态以触发渲染。
init() {
window.onresize = () => {
setTimeout(() => this.computeNumCards(),1000);
};
}
,
window.addEventListener代替了使用window.onresize,从而解决了这个问题。
window.addEventListener("resize",() => setTimeout(() => this.computeNumCards(),100));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。