首页 > 解决方案 > React js,如何使用xml作为你的html设计

问题描述

我有一个从生成 xml 文件的 cms 工具创建的页眉/页脚。

我的 xml: https ://uhf.microsoft.com/en-US/shell/xml/MSIrelandsFuture?headerId=MSIrelandsFutureHeader&footerid=MSIrelandsFutureFooter

我的代码:

import React, { useState, useEffect } from "react";
import axios from "axios";


export default function RegisterEntry() {
    const [xml, setXML] = useState('');

    axios.get('https://uhf.microsoft.com/en-US/shell/xml/MSIrelandsFuture?headerId=MSIrelandsFutureHeader&footerid=MSIrelandsFutureFooter', {
        "Content-Type": "application/xml; charset=utf-8"
    })
        .then((response) => {
            console.log('Your xml file as string', response.data);
            setXML(response.data)
        });




    return (
        <React.Fragment>
            {xml}
        </React.Fragment >
    )
}

这些以某种方式返回了我的 xml 文本,我不确定如何返回实际的 ui 设计

返回: 在此处输入图像描述

我想要的结果:

在此处输入图像描述

标签: reactjs

解决方案


使用DOMParser将 XML 或 HTML 源代码从字符串解析为 DOM 文档。获取所需的节点并将其附加到文档的某些部分:

const appendToNode = (node, content) => {
    node.innerHTML += content;
  };

  useEffect(() => {
    const DOMParse = new DOMParser();
    let xmlDoc;
    axios
      .get(
        'https://uhf.microsoft.com/en-US/shell/xml/MSIrelandsFuture?headerId=MSIrelandsFutureHeader&footerid=MSIrelandsFutureFooter',
        {
          'Content-Type': 'application/xml; charset=utf-8'
        }
      )
      .then(response => {
        xmlDoc = DOMParse.parseFromString(response.data, 'text/xml');
        appendToNode(
          ref.current //--> some node in your document
          xmlDoc.querySelector('headerHtml').textContent //--> do the same with the rest of the nodes
        );
      })
      .catch(err => console.log(err));
  }, []);

工作示例

我建议您使用html-react-parser库将 HTML 字符串转换为 JSX 元素。


推荐阅读