lak*_*are 5 html javascript jsx reactjs babeljs
我有: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/>.
你可能想看看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);
}
}
Run Code Online (Sandbox Code Playgroud)
这里的重要部分是processingInstructions. DOM 树中的每个节点都根据数组中的每条指令进行检查,从顶部开始,直到shouldProcessNode返回 true,然后该节点被相应的processNode函数转换为 React 元素。这允许相当复杂的处理规则,但如果您想处理嵌套的自定义元素,它很快就会变得有点混乱。该示例的结果相当于
<h1>
Hi
<MyReactComponent/>
</h1>
Run Code Online (Sandbox Code Playgroud)
在 JSX 语法中。希望这可以帮助!