从普通JSX外部脚本从运行时加载一个React组件

发布于 2025-01-27 03:05:05 字数 151 浏览 4 评论 0原文

一般而言,我必须在运行时加载和渲染的选项是什么,我在未编译的JSX Plain脚本中拥有的React组件是:也许是从字符串或URL中。显然,组件脚本可以从同一应用的其他(静态)组件或其他外部软件包中导入。

注意:这是针对公司的内部网络应用程序,也就是说,没有强大的安全要求。

In general terms, what are the options that I have to load and render in runtime a React component that I have in an uncompiled JSX plain script somewhere: maybe from a string or from a url. Obviously the component script can have imports from other (static) components of the same app or from other external packages.

Note: it's for an internal web app of a company, that is, there are no strong security requirements.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最后的乘客 2025-02-03 03:05:05

我知道这样的唯一简单选择是使用babel独立,它可以在客户端对JS转换进行JSX。将JSX字符串插入< script type =“ text/babel”>,并包括react,react dom和babel独立作为页面上的脚本。

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div class='react'></div>

<script>
const jsxTextToInsert = `
    const App = () => {
        return 'foo';
    };

    ReactDOM.render(<App />, document.querySelector('.react'));
`;

const script = document.body.appendChild(document.createElement('script'));
script.type = 'text/babel';
script.textContent = jsxTextToInsert;
</script>

The only easy-ish option I'm aware of for something like that is to use Babel Standalone, which does JSX to JS transformation on the client-side. Insert the JSX string into a <script type="text/babel">, and include React, React DOM, and Babel Standalone as scripts on the page.

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div class='react'></div>

<script>
const jsxTextToInsert = `
    const App = () => {
        return 'foo';
    };

    ReactDOM.render(<App />, document.querySelector('.react'));
`;

const script = document.body.appendChild(document.createElement('script'));
script.type = 'text/babel';
script.textContent = jsxTextToInsert;
</script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文