【问题标题】:How to render a user defined react component?如何呈现用户定义的反应组件?
【发布时间】:2023-02-14 11:27:28
【问题描述】:

在我的电子应用程序中,我想为 UI 提供某种可扩展性。 用户应该能够在我的应用程序内的文本编辑器内创建一个反应组件。他们的代码被保存到一个文件中。他们还可以定义组件在我的 UI 中的放置位置。

问题是:我似乎无法弄清楚如何在我现有的 React 应用程序中解析和注入用​​户定义的 JSX。

我以为我尝试使用 babel transformSync,但我无法让它工作。这是我到目前为止所拥有的:

const DynamicComponent = (props) => {
  const reactCode = `
    return (
      <div>
        <h1 >Hello, World!</h1>
      </div>
    )
  `;

  const transpiledCode = transform(reactCode, {
    presets: ["@babel/preset-react"]
  }).code;

  console.log("transpiled", transpiledCode);
  globalThis["React"] = React;
  const Dynamic = new Function(`return ${transpiledCode}`)();
  return <Dynamic />;
};

https://codesandbox.io/s/mobx-state-tree-todolist-3umd4?file=/components/TodoList.js

我想在待办事项列表下方显示“&lt;h1&gt;Hello, World!&lt;/h1&gt;”。

【问题讨论】:

    标签: javascript reactjs babeljs


    【解决方案1】:

    这花了一些时间。以下是需要注意的事项:

    1. @babel/core 给出了无效的版本错误,所以我使用了 @babel/runtime 版本,因为它是为在浏览器中使用而设计的。
    2. 我发现在使用 @babel/core 时删除 cmets 有助于解决 js 的自动分号插入问题。
    3. 您需要直接返回新的 DynamicComponent。不要通过返回 &lt;Dynamic /&gt; 将其转换为 ReactElements。

      见codesandboxhere

      const DynamicComponent = (props) => {
        const reactCode = `
             <div>
                <h1>Hello, World!</h1>
              </div>
        `;
      
        const transpiledCode = transform(reactCode, {
          presets: [
            "react",
            {
              comments: false
            }
          ]
        }).code;
      
        globalThis["React"] = React;
      
        return new Function(`return ${transpiledCode}`)();
      };

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 2017-05-12
      • 2019-09-24
      • 2015-08-31
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      相关资源
      最近更新 更多