1 回答

TA貢獻1780條經驗 獲得超5個贊
我們可以嘗試在 React 上下文中添加動態元素。
export const overFlowIcon = (element) => {
const oldId = element.querySelectorAll(‘#myID’); // add someId inside to icon and check may Be in case content re renders in React
setTimeout(() => {
const pDiv = element.getBoundingClientRect();
const imgTags = element.querySelectorAll("img");
imgTags.forEach(imgTag => {
const imdDiv = imgTag.getBoundingClientRect();
if (imdDiv.width > pDiv.width) {
const parent = imgTag.parentNode;
parent.style.width = '100%';
const cont = document.createElement('div');
const wrap = document.createElement('div');
cont.classList.add(‘stickycontainer');
wrap.classList.add(‘horizontalScroll');
container.appendChild(wrap);
parent.replaceChild(container, imgTag);
wrap.appendChild(imgTag);
const newE = document.createElement('span'); // creating icon
newE.onclick = (event) => (element.scrollBy(100, 0); event.stopPropagation();)
newE.classList.add(‘arrow'); // styling a problem can fix
wrap.appendChild(newE);
}
});
}, 0);
};
.stickycontainer
position: relative;
}
.horizontalScroll {
overflow-x: auto;
display: flex;
}
.arrow {
position: absolute;
left: 80%;
top: 50%;
border: solid #000;
border-width: 0 3px 3px 0;
display: inline-block;
padding: 3px;
cursor: pointer;
transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
}
在這種情況下,我們確保元素在視圖中,然后使用 JS 進行轉換,同時為了防止重新渲染的效果,我們可以將 id 添加到任何元素,然后如果 React 重新渲染,我們可以檢查 id 是否存在,我們可以防止通過防止重新渲染的影響,整個方法一起運行,或者可以向該方法添加一個額外的參數。
更新添加 React Ref 后,由于內容以字符串形式出現,您可以使用 DOM 解析器將其轉換為您的格式并返回字符串,然后在 React Context 本身中添加邏輯,例如
export const horizontalOverflow = (content) => {
const parser = new DOMParser();
const doc = parser.parseFromString(content, 'text/html');
const element= doc.body;
if (element) {
const imgTags = element.querySelectorAll("img");
imgTags.forEach(imgTag => {
const parent = imgTag.parentNode;
const wrapper = document.createElement('span');
wrapper.classList.add(horizontalscrolling);
parent.replaceChild(wrapper, imgTag);
wrapper.appendChild(imgTag);
});
}
return element.outerHTML;
};
現在您可以使用它來創建標記。
- 1 回答
- 0 關注
- 209 瀏覽
添加回答
舉報