2

我正在从服务器获取 html 模板。该模板里面也有对象数据。我想在反应组件中显示该模板。我设法使用 html-react-parser 插件显示所有 html 元素,但我的变量呈现为字符串 {data.title}。

const Template = ({templateData}) => {

    const [data, setData] = useState({
        title: 'Some title',
        description: 'Some description'                    
    })

    return(
        <Fragment>
            {HtmlParser(templateData)}
        </Fragment>
    )
};

编译为:

<div>
    <div class="title">{data.title}</div>
    <div class="description">{data.description}</div>
</div>

想要的结果:

<div>
    <div class="title">'Some title'</div>
    <div class="description">'Some description'</div>
</div>

编辑:找到了解决方案,但它看起来不是一个好的解决方案:) 我用变量替换了字符串。

   HtmlParser(templateData
                 .replace(/{data.title}/g, data.title)
                 .replace(/{data.description}/g, data.description))
4

0 回答 0