如何将 React 组件放入 HTML 字符串中?

How to put React component inside HTML string?

我有:HTML 个字符串数组,例如["<h1>Hi", "</h1>"]。
我想在它们之间放置 <MyReactComponent/>
(从而实现在 jsx 中的布局:
<h1>Hi<MyReactComponent/></h1>).

如何实现?


我试过:

您可能想看看 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 returns 为真,并且该节点通过相应的 processNode函数。这允许相当复杂的处理规则,但如果你想处理嵌套的自定义元素,它很快就会变得有点混乱。该示例的结果相当于

<h1>
    Hi
    <MyReactComponent/>
</h1>

在 JSX 语法中。希望这对您有所帮助!