我有一个HTML 字符串数组, eg ["<h1>Hi", "</h1>"
].
我想放置<MyReactComponent/>
在他们之间
(从而实现 jsx 中的布局:
<h1>Hi<MyReactComponent/></h1>
).
我该如何实现这一目标?
我试过了:
Babel.transform('<h1>Hi<MyReactComponent/></h1>')
(使用独立的 Babel)。它确实有效,但需要我进行字符串化<MyReactComponent/>
, 这并不优雅,并且可能有一天会崩溃.
使用常规 jsxrender() => <MyReactComponent/>
,然后,在componentDidMount
通过操作 DOM 添加 HTML,但浏览器会自动插入结束标签,所以我会得到<h1>Hi</h1><MyReactComponent/><h1></h1>
to use jsx-to-html
图书馆和innerHTML
, 转换<MyReactComponent/>
到 HTML 字符串,将其与<h1>Hi</h1>
,但它破坏了与的任何 React 交互<MyReactComponent/>
.
您可能想看一下html 反应 https://github.com/mikenikles/html-to-react.
该库将字符串转换为 DOM 元素的节点树,然后使用您定义的一组指令将每个节点转换为 React 元素。我相信这取决于字符串是有效的标记,所以你可能需要改变"<h1>Hi<MyReactComponent/></h1"
类似的东西"<h1>Hi<x-my-react-component></x-my-react-component></h1>
.
Example:
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,该节点通过相应的方法转换为React元素processNode
功能。这允许相当复杂的处理规则,但如果您想处理嵌套的自定义元素,它很快就会变得有点混乱。该示例的结果相当于
<h1>
Hi
<MyReactComponent/>
</h1>
在 JSX 语法中。希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)