简体   繁体   中英

React render components from string

Is it possible to dynamically render a React component from a string?

Basically I have pages' content coming from the database and I want to have React componentes within the content. An example of what I'm trying to achieve:

var html_string = '<i>React Component Rendered</i>: <Hello name="World" />';

var Hello = React.createClass({
  render: function() {
    return <strong>Hello {this.props.name}</strong>;
  }
});

function createMarkup() { return {__html: html_string}; };

var App = React.createClass({
  render: function() {
    return <div dangerouslySetInnerHTML={createMarkup()} />;
  }
});

ReactDOM.render(
  <App/>,
  document.getElementById('container')
);

But it just renders the HTML without evaluating <Hello/> :

<div><i>React Component Rendered</i>: <hello name="World"></hello></div>

I'm trying to get:

<div><i>React Component Rendered</i>: <strong>Hello World</strong></div>

This example on JSfiddle: https://jsfiddle.net/26czprne/

As thangngoc89 as said there is no way to do this. At least no simple way.

JSX is transpiled into javascript, it only syntactically looks like xml.

this:

var x = <div> <i>React Component Rendered</i>: <Hello name="World" /> </div>;

is mapped to:

var x = React.createElement(
  "div",
  null,
  " ",
  React.createElement(
    "i",
    null,
    "React Component Rendered"
  ),

  ": ",
  React.createElement(Hello, { name: "World" }),
);

A better strategy would probably be to parse the database elements and then dynamically render the result of the db query using react (this also promotes looser coupling).

Might be a little late to the party one this one, but have found myself needing to do slightly similar to this and after searching the web, I've found that this is actually technically possible now (safety issues aside) - with the addition of a nice little react package:

https://github.com/TroyAlford/react-jsx-parser

import React, { Component } from 'react'
import JsxParser from 'react-jsx-parser'

class InjectableComponent extends Component {
  // ... inner workings of InjectableComponent
}

class MyComponent extends Component {
  render() {
    /* Pull out parent props which shouldn't be bound,
       then pass the rest as `bindings` to all children */
    const { prop1, prop2, ...bindings } = this.props

    return (
      <JsxParser
        bindings={bindings}
        components={{ InjectableComponent }}
        jsx={'\
          <h1>Header</h1>\
          <InjectableComponent />\
        '}
      />
    )
  }
}

all credit to TroyAlford!

what you are asking is not possible. React will dump what ever string you provided via dangerouslySetInnerHTML . It will not evaluating anything inside it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM