reactjs - 使用 React 和 TypeScript 加载自定义 HTML 元素的正确方法是什么?
所以我正在尝试在我的网站上加载一些 LaTeX,但我不确定这是否是最佳方法,希望获得一些建议,因为我对 TypeScript 比较陌生。
main.tsx
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<CssBaseline />
<Latex path="/latex/latex.tex"/>
<TextBox></TextBox>
<App />
</ThemeProvider>
</React.StrictMode>,
);
index.html
<script type="module">
import { LaTeXJSComponent } from "https://cdn.jsdelivr.net/npm/latex.js/dist/latex.mjs"
customElements.define("latex-js", LaTeXJSComponent)
</script>
<style>
latex-js {
display: inline-block;
width: 55%;
border: 1px solid rgb(0, 0, 0);
margin-right: 2em;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
App.tsx:
import * as React from 'react';
import { useEffect, useState } from 'react';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import TextareaAutosize from '@mui/base/TextareaAutosize';
import { styled } from "@mui/material/styles";
import Button from '@mui/material/Button';
import SendIcon from '@mui/icons-material/Send'
import { Alert } from '@mui/material';
declare global {
namespace JSX {
interface IntrinsicElements {
'latex-js': any;
}
}
}
export function Latex({ path }: { path: string }) {
const [fileContent, setFileContent] = useState('');
useEffect(() => {
async function fetchFile() {
try {
const response = await fetch(path);
const text = await response.text();
setFileContent(text);
} catch (error) {
console.error('Error fetching file:', error);
}
}
fetchFile();
}, []);
return (
<center>
<div>
<latex-js>{fileContent}</latex-js>
</div>
</center>
);
}
我目前的方法是将脚本导入到 HTML 中,创建一个名为“latex-js”的自定义 HTML 元素,然后在 App.tsx 文件中从一个文件加载 LaTeX 数据并将其作为标签注入。由于我对整个 web 开发还很陌生,我在想是否有人知道处理这种事情的更好方法。