React render components from string

依然范特西╮ 提交于 2020-01-11 03:52:30

问题


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/


回答1:


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).




回答2:


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!




回答3:


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



来源:https://stackoverflow.com/questions/36520714/react-render-components-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!