2016-04-09 8 views
1

Reactコンポーネントを文字列から動的にレンダリングすることはできますか?文字列からレンダリングコンポーネントを返す

基本的に私はデータベースからのページのコンテンツを持っており、コンテンツ内にReactコンポーネントが必要です。

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

をしかし、それはちょうど<Hello/>を評価せずにHTMLをレンダリングします::

<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/

答えて

1

thangngoc89と同じように、これを行う方法はありません。少なくとも単純な方法ではありません。

JSXはjavascriptに変換され、構文的にはxmlのように見えます。

これ:

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

がマップされている:よりよい戦略は、おそらくデータベース要素を解析し、動的に反応する使用DBクエリの結果をレンダリングすることであろう

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

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

(これもより疎結合を促進する)。

+0

ありがとう、あなたのためのアイデア@ mason505私はあなたのアプローチを使用して私のプロジェクトでそれを実装しました。ここに私の例があります:https://jsfiddle.net/ex77v29g/2/ 'componentDidMount'の中で' ReactDOM.render'を使うのは良い考えです。私は後で再考します。 – Alisson

0

あなたが求めているものはありません。 ReactはdangerouslySetInnerHTMLであなたが提供した文字列をダンプします。それはそれの中の何かを評価しません。

0

これに少し遅れているかもしれませんが、これと少し似ている必要があり、Webを検索した後で、これは現在技術的に可能であることがわかりました。ちょっといい反応するパッケージを追加した:

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 />\ 
     '} 
     /> 
    ) 
    } 
} 

TroyAlfordへのすべてのクレジット!

関連する問題