render React component from a string

后端 未结 2 1328
半阙折子戏
半阙折子戏 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:35

    React will allow you to render either a Component or an Element. You can think of an Element as a raw HTML code in JSX, while a Component is a prototype, which inherits from React.Component. In your code you are trying to render a result of evaluating the babel transpiled code, which will fail (I'm not sure what it is, but it's probably undefined or null). If you want to make it work, first evaluate the code and then invoke the function to pass the Element code to the render function:

    eval(babelCode);  // now the App function has been defined and you can use it in the code
    render(App(), document.getElementById('WorkFlow'));
           // ^^ here the App function is being invoked
    

    Old answer (I thought you were trying to pass the component as a file not and not as a variable to transpiler):

    babel will never transpile strings, so this is not going to work out for you. You can however consider using a raw JS code instead of JSX as your string content. More about it you can read here: https://facebook.github.io/react/docs/react-without-jsx.html

提交回复
热议问题