[英]How to put React component inside HTML string?
我有: 一串HTML字符串 ,例如["<h1>Hi", "</h1>"
]。
我想在它們之間放置<MyReactComponent/>
(從而實現了jsx中的布局:
<h1>Hi<MyReactComponent/></h1>
)。
我該如何實現這一目標?
我試過了:
Babel.transform('<h1>Hi<MyReactComponent/></h1>')
(使用獨立的Babel)。 它確實有效,但需要我對<MyReactComponent/>
進行字符串化, 這不是優雅的,可能會在某一天中斷 。
使用常規jsx render() => <MyReactComponent/>
,然后,在componentDidMount
通過操作DOM來預先添加HTML, 但是瀏覽器會自動插入結束標記 ,所以我將獲得<h1>Hi</h1><MyReactComponent/><h1></h1>
使用jsx-to-html
庫和innerHTML
,將<MyReactComponent/>
轉換為HTML字符串,將其與<h1>Hi</h1>
,但它會破壞與<MyReactComponent/>
任何React交互。
你可能想看看html-to-react 。
此庫將字符串轉換為DOM元素的節點樹,然后使用您定義的一組指令將每個節點轉換為React元素。 我相信它依賴於字符串是有效標記,所以你可能不得不將"<h1>Hi<MyReactComponent/></h1"
更改為"<h1>Hi<x-my-react-component></x-my-react-component></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
。 DOM樹中的每個節點都會根據數組中的每條指令進行檢查,從頂部開始,直到shouldProcessNode
返回true,並通過相應的processNode
函數將節點轉換為React元素。 這允許相當復雜的處理規則,但如果要處理嵌套的自定義元素,它會很快變得有點混亂。 該示例的結果相當於
<h1>
Hi
<MyReactComponent/>
</h1>
在JSX語法中。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.