How do I convert a string to jsx?

前端 未结 8 1961
Happy的楠姐
Happy的楠姐 2020-11-27 20:19

How would I take a string, and convert it to jsx? For example, if I bring in a string from a textarea, how could I convert it to a React

相关标签:
8条回答
  • 2020-11-27 20:44

    I came across this answer recently and, it was a good deal for me. You don't need to provide a string. Returning an array of JSX elements will do the trick.

    We can store JSX elements in JavaScript array.

    let arrUsers = [<li>Steve</li>,<li>Bob</li>,<li>Michael</li>];
    

    and in your HTML (JSX) bind it like,

    <ul>{arrUsers}</ul>
    

    As simple as it is.

    0 讨论(0)
  • 2020-11-27 20:48

    Here's a little utility component for this:

    const RawHtml = ({ children="", tag: Tag = 'div', ...props }) =>
      <Tag { ...props } dangerouslySetInnerHTML={{ __html: children }}/>;
    

    Sample usage:

    <RawHtml tag={'span'} style={{'font-weight':'bold'}}>
      {"Lorem<br/>ipsum"}
    </RawHtml>
    
    0 讨论(0)
提交回复
热议问题