render React component from a string

后端 未结 2 1298
半阙折子戏
半阙折子戏 2021-01-23 22:05

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

const component = `
function App() {
  return (
    
test
); } `;

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 22:32

    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(, document.getElementById('WorkFlow'));
    

    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.

    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(, document.getElementById('WorkFlow'));
    

    Hope this helps!

提交回复
热议问题