Replace part of string in WYSIWYG editor using JSX
P粉060112396
P粉060112396 2023-08-17 10:28:01
0
1
523
<p>I have a string provided by WYSIWYG editor input, for example: </p> <pre class="brush:js;toolbar:false;">const originalString = "<div>Some text</div><strong>Some bold text{{response}}</strong> "; </pre> <p>I need to replace <code>{{response}}</code> with some JSX and output the result as HTML. </p> <p>I don't think I can use <code>dangerouslySetInnerHTML</code> because it doesn't handle JSX. Instead, you get the following output: </p> <pre class="brush:html;toolbar:false;"><div>Some text</div> <strong>Some bold text [object Object]</strong> </pre> <p>View examples here. </p> <p>Is there a way to replace <code>{{response}}</code> with JSX and then convert the rest of the string to valid HTML when rendering? </p>
P粉060112396
P粉060112396

reply all(1)
P粉486138196

Is this what you want?

import React, {renderToString} from "react";
import "./style.css";
import * as ReactDOMServer from 'react-dom/server';

export default function App() {
  return (
    <StringReplacement />
  );
}

class StringReplacement extends React.Component {
  render() {
    //这可以是从所见即所得编辑器中作为字符串的任何有效的HTML
    const originalString = "<div>some text</div><strong>some strong text {{response}}</strong>";

    // 用JSX内容替换'{{response}}'
    const jsxReplacement = <span onClick={ () => alert('')}>JSX content here</span>;
    const replacedString = originalString.replace('{{response}}', ReactDOMServer.renderToString(jsxReplacement));

    return (
      <div>
        <div dangerouslySetInnerHTML={{ __html: replacedString }} />
      </div>
    );
  }
}

export default StringReplacement;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template