从字符串中反映渲染组件 [英] React render components from string

查看:55
本文介绍了从字符串中反映渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从字符串中动态呈现React组件?

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

基本上我有来自数据库的页面内容,我希望在其中包含React组件内容。我想要实现的一个例子:

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')
);

但它只是渲染HTML而不评估< Hello />

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

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

我想得到:

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

这个关于JSfiddle的例子: https://jsfiddle.net/26czprne/

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

推荐答案

正如thangngoc89所说的那样没办法做到这一点。至少没有简单的方法。

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

JSX被转换为javascript,它只在语法上看起来像xml。

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

这个:

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

映射到:

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

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

更好的策略可能是解析数据库元素然后动态呈现db查询的结果使用react(这也促进了更松散的耦合)。

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

这篇关于从字符串中反映渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆