我的目標是從我自己的服務器獲取 SVG 并children在標記后插入屬性<polygon></polygon>。
我這樣做是為了添加一個可以通過react修改的互動層。
到目前為止,我可以通過 react 應用程式提供我的 SVG 來實作這一點,但出于安全原因,我想避免它。
這是我到目前為止的進展:
const App = ({children}) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="#6b9bd2"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="arcs"
>
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
{children}
</svg>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
我理想的解決方案應該是這樣的:
import React, { useState, useEffect } from "react";
type ViewBox = {
x1: string;
x2: string;
y1: string;
y2: string;
};
interface SVGElement {
svgContent: string;
viewBox: ViewBox;
}
const App: React.FC = ({ children }) => {
const [content, setContent] = useState<SVGElement | undefined>();
useEffect(() => {
fetch("http://localhost:5000/get-svg-content")
.then((res) => res.json())
.then((data) => setContent(data))
.catch((e) => console.log(e));
}, []);
if (content === undefined) return <></>;
const viewBox = `${content.viewBox.x1} ${content.viewBox.x2} ${content.viewBox.y1} ${content.viewBox.y2}`;
return (
<svg viewBox={viewBox}>
{content.svgContent}
{children}
</svg>
);
};
export default App;
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
代碼沙盒
uj5u.com熱心網友回復:
您應該考慮使用rehype-react- https://github.com/rehypejs/rehype-react。
例如,如果您將 SVG 作為 XML 存盤在資料庫中,然后在客戶端將其作為字串檢索,則此包允許您將相同的字串呈現為 SVG(或任何其他標簽)。
此方法可能會將您暴露給 XSS,因此您應該考慮使用react-sanitize以在渲染字串之前對其進行清理。
使用上面提到的方法,您可以在react客戶端內渲染您的 SVG 元素,并且仍然圍繞渲染的內容實作您的組件邏輯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481561.html
標籤:javascript 反应 svg
上一篇:為什么SVGR沒有在我的esbuild配置中生成TypeScript宣告檔案?
下一篇:如何從網站下載影片SVG檔案?
