【问题标题】:How to put React component inside HTML string?如何将 React 组件放入 HTML 字符串中?
【发布时间】:2016-12-22 05:59:17
【问题描述】:

我有: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 交互。

    李>

【问题讨论】:

  • 你试过用React.createElement解析字符串来创建DOM吗?这是一个选项还是您只想生成jsx
  • 绝对是一种选择。

标签: javascript html reactjs jsx babeljs


【解决方案1】:

您可能想看看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 语法中。希望这会有所帮助!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2013-09-22
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多