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>
に相当します。お役に立てれば!
DOMを作成するために 'React.createElement'で文字列を解析しようとしましたか?これはオプションか、 'jsx'だけを生成したいのですか? – melc
それは絶対にオプションです。 – lakesare