[英]es6 object destructuring not working
我正在嘗試為對象分配樣式。 初始代碼為
targetEl.style.top = `${top}px` ;
targetEl.style.display = 'block';
targetEl.style.background = `url(${this.props.imgSrc}) no-repeat`;
targetEl.style.backgroundSize = "1800px 900px";
我試圖使用es6解構並重寫了如下代碼:
targetEl.style = {...targetEl.style,
top:`${top}px`,
display: 'block',
background: `url(${this.props.imgSrc}) no-repeat`,
backgroundSize: "1800px 900px" };
但是由於某種原因,它似乎不起作用。 我究竟做錯了什么?
您未使用解構,而是在創建新對象的對象文字中使用實驗性擴展語法。 在使用不可變數據框架時,您可能已經習慣了這一點,但是在這里,您確實要分配 targetEl.style
CSS聲明對象的屬性 。 您不想用一個新的替換整個.style
對象。
嘗試使用普通文字來進行Object.assign
:
Object.assign(targetEl.style, {
top: `${top}px`,
display: 'block',
background: `url(${this.props.imgSrc}) no-repeat`,
backgroundSize: '1800px 900px'
});
附帶說明一下,如果沒有Object.assign
效率會更高:
const s = targetEl.style;
s.top = `${top}px`;
s.display = 'block';
s.background = `url(${this.props.imgSrc}) no-repeat`;
s.backgroundSize = '1800px 900px';
但是更高效地一次分配它們( 如何在JavaScript中設置多種CSS樣式? ):
targetEl.style.cssText += `; top = ${top}px, display = 'block',
background = url(${this.props.imgSrc}) no-repeat, backgroundSize = '1800px 900px'; `;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.