嗨,為了優化我巨大的 svg 組件,我正在嘗試做與本教程類似的事情:https ://medium.com/@ians/rendering-svgs-as-images-directly-in-react-a26615c45770 ,到目前為止我我想出了這個
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server'
function Image({children}) {
let draw = <svg xmlns="http://www.w3.org/2000/svg">{children}</svg>
let svgToMiniDataURI = require('mini-svg-data-uri')
let image = svgToMiniDataURI(renderToStaticMarkup(draw))
return <image href={image} />
}
export default Image
它作業得很好,但我不想使用 renderToStaticMarkup 有一個原因:我在我的 SVG 組件中使用 getBBox 方法,這真的很難避免使用。
關于如何在不使用 SSR 的情況下實作類似目標的任何想法?或者任何讓 getBBox 在服務器端作業的方法(我看到了 phantomjs,但我認為這會降低性能而不是幫助,而且它似乎不是一個很好的解決方案)
uj5u.com熱心網友回復:
因此,這樣做的替代方法是獲取我們在頁面中加載的組件的參考,在 React 呈現后獲取其 html 內容,然后對其進行更改。這是我的示例函式 Image({children}) { let svgToMiniDataURI = require('mini-svg-data-uri') 的代碼
const imageContainer = React.useCallback(node => {
if (node !== null) {
Image.timer = setTimeout(()=>{ //I used this delay so my component get its useEffects done
const image = svgToMiniDataURI(node.outerHTML)
//here we could have also set a state with the href value and then based on that state in the return we choose to render the image instead of the normal comp
if (node.parentNode)
node.outerHTML = `<image href="${image}" />`
}, 0.1)
}
}, [])
React.useEffect(() => {
return () => {
clearTimeout(Image.timer);
}
}, [])
return <svg xmlns="http://www.w3.org/2000/svg" ref={imageContainer}>{children}</svg>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459439.html
下一篇:SVG高度未按預期運行
