Javascript 如何将React组件放入HTML字符串中?
我有:一个HTML字符串的数组,例如Javascript 如何将React组件放入HTML字符串中?,javascript,html,reactjs,jsx,babeljs,Javascript,Html,Reactjs,Jsx,Babeljs,我有:一个HTML字符串的数组,例如[“Hi”,“”。 我想把放在它们之间 (从而实现jsx中的布局: Hi) 我如何做到这一点 我试过: Babel.transform('Hi')(使用独立的Babel)。它确实有效,但需要我将,字符串化,这并不优雅,可能有一天会中断 要使用常规的jsxrender()=>,然后在componentDidMount上通过操作DOM预处理HTML,但浏览器会自动插入结束标记,因此我将获得Hi 要使用jsx到html库和innerHTML,要将转换为html字
[“Hi”,“
”。我想把
放在它们之间(从而实现jsx中的布局:
Hi
)
我如何做到这一点
我试过:
(使用独立的Babel)。它确实有效,但需要我将Babel.transform('Hi')
,字符串化,这并不优雅,可能有一天会中断- 要使用常规的jsx
,然后在render()=>
上通过操作DOM预处理HTML,但浏览器会自动插入结束标记,因此我将获得componentDidMount
Hi
- 要使用
库和jsx到html
,要将innerHTML
转换为html字符串,请将其与
组合,但它会破坏与Hi
的任何交互
该库将字符串转换为DOM元素的节点树,然后使用您定义的一组指令将每个节点转换为React元素。我相信这取决于字符串是否是有效的标记,因此您可能必须更改
“您是否尝试使用React.createElement
解析字符串以创建DOM?这是一个选项,还是您只希望生成jsx
?这绝对是一个选项。(如果有人感兴趣,这里是我的最终实现)
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);
}
}
<h1>
Hi
<MyReactComponent/>
</h1>