2016-08-16 2 views
3

私は:のHTML文字列の配列、例えば["<h1>Hi", "</h1>"]を持っています。
私は
それらの間に<MyReactComponent/>を配置したい(これJSXになるレイアウトを実現:
<h1>Hi<MyReactComponent/></h1>)。ReactコンポーネントをHTML文字列に入れる方法は?

どうすればよいですか?


私が試してみた:

  • Babel.transform('<h1>Hi<MyReactComponent/></h1>')(スタンドアロンバベルを使用)。それは動作しますが、私は<MyReactComponent/>を文字列化する必要があります。これはエレガントではないし、おそらくある日、を破るでしょう。 、

  • はJSX render() => <MyReactComponent/>定期的に使用するには、その後、HTMLを付加componentDidMountにDOM、を操作することではなく、ブラウザは終了タグを自動的を挿入しますので、私はjsx-to-htmlライブラリとinnerHTMLを使用する<h1>Hi</h1><MyReactComponent/><h1></h1>

  • を取得することがあります<MyReactComponent/>をHTMLの文字列に変換するには、<h1>Hi</h1>と組み合わせてください。しかし、それは<MyReactComponent/>とのリアクションの相互作用を破壊します。

+0

DOMを作成するために 'React.createElement'で文字列を解析しようとしましたか?これはオプションか、 'jsx'だけを生成したいのですか? – melc

+0

それは絶対にオプションです。 – lakesare

答えて

2

html-to-reactをご覧ください。

このライブラリは文字列をDOM要素のノードツリーに変換し、定義した一連の命令を使用して各ノードをReact要素に変換します。私はそれが有効なマークアップである文字列に依存すると信じているので、"<h1>Hi<x-my-react-component></x-my-react-component></h1>のようなものに"<h1>Hi<MyReactComponent/></h1"を変更しなければならないかもしれません。

例:

import { Parser, ProcessNodeDefinitions } from "html-to-react"; 
import MyReactComponent from "./MyReactComponent"; 

const customElements = { 
    "x-my-react-component": MyReactComponent 
}; 

// Boilerplate stuff 
const htmlParser = new Parser(React); 
const processNodeDefinitions = new ProcessNodeDefinitions(React); 
function isValidNode(){ 
    return true; 
} 

// Custom instructions for processing nodes 
const processingInstructions = [ 
    // Create instruction for custom elements 
    { 
     shouldProcessNode: (node) => { 
      // Process the node if it matches a custom element 
      return (node.name && customElements[node.name]); 
     }, 
     processNode: (node) => { 
      let CustomElement = customElements[node.name]; 
      return <CustomElement/>; 
     } 
    }, 
    // Default processing 
    { 
     shouldProcessNode:() => true, 
     processNode: processNodeDefinitions.processDefaultNode 
    } 
]; 

export default class MyParentComponent extends Component { 
    render() { 
     let htmlString = "<h1>Hi<x-my-react-component></x-my-react-component></h1>"; 
     return htmlParser.parseWithInstructions(htmlString, isValidNode, processingInstructions); 
    } 
} 

ここで重要な部分は、processingInstructionsです。 がtrueを返すまで、DOMツリー内の各ノードが配列内の各命令に対してチェックされ、対応するprocessNode関数によってノードがReact要素に変換されます。これにより、かなり複雑な処理ルールが可能になりますが、ネストされたカスタム要素を処理する場合は、ちょっと混乱します。この例の結果は、JSX構文で

<h1> 
    Hi 
    <MyReactComponent/> 
</h1> 

に相当します。お役に立てれば!

+0

私の状況にはかなり完璧です、ありがとうございます。 – lakesare

+1

(ここに私の最終的な実装があります。誰かが興味を持っている場合はhttps://github.com/lakesare/memcode/blob/c049ae23ecabbd502116c440ff8b2d39fd14be88/frontend/services/problemContentToJsx.js) – lakesare

関連する問題