从字符串渲染React组件 [英] render React component from a string

查看:572
本文介绍了从字符串渲染React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在字符串中有一些React代码,例如:

I have some React code in the string, for example:

const component = `
function App() {
  return (
    <div>
    test
    </div>
  );
}
`;

我希望能够从浏览器中渲染该组件,例如:

And I want to be able to render that component from within browser, something like:

import React, { Component } from 'react';
import { render } from 'react-dom';
import * as babel from 'babel-standalone';


const babelCode = babel.transform(component, { presets: ['react', 'es2015'] }).code;

render(eval(babelCode), document.getElementById('WorkFlow'));

此特定示例不起作用,但它显示了我正在寻找的内容,感谢您的帮助!

This particular example doesn't work but it shows what I'm looking for, any help appreciated!

谢谢!

推荐答案

Babel使用"use strict"生成代码,而eval()不能很好地使用它.首先,我们应该手动删除该行.

Babel produces the code with "use strict" and eval() doesn't work with it well. First, we should remove that line manually.

const code = babelCode.replace('"use strict";', "").trim();

理想地,在此之后,以下几行应该起作用.

Ideally, after this following lines should work.

eval(code);
render(<App/>, document.getElementById('WorkFlow'));

请注意,您无需将eval()放入渲染器中.它不会返回您的App函数或其他任何内容.而是将App添加到上下文中,我们可以在eval()语句之后使用它.

Note that you don't need to put eval() inside render. It doesn't return your App function or anything. Instead, it will add App to context and we can use it after eval() statement.

但是通常,React应用程序具有使用webpack或类似工具的编译步骤,并且会抱怨未定义的App.

But usually, React app has a compile step with webpack or similar tool and will complain about undefined App.

作为一种解决方法,我们可以使用

As a workaround, we can wrap our component with a Function which returns our component itself. Now we can call this function to get our component. But the context of wrapping function doesn't have React variable. So we have to pass it manually as a parameter. If you are going to use any other variable from the current context, you will have to pass those as well.

const code = babelCode.replace('"use strict";', "").trim();
const func = new Function("React", `return ${code}`);
const App = func(React)
render(<App/>, document.getElementById('WorkFlow'));

希望这会有所帮助!

这篇关于从字符串渲染React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆