我怎样才能渲染出来 标签与反应?

问题描述 投票:4回答:1

有时您可能需要从您的反应应用程序渲染Web组件。

Web组件通常使用特殊的<template> ... </template>标记。但是,如果我尝试使用这样的反应来呈现这样的标记:

render() {
  return (
    <template>
      <div>some content</div>
    </template>
  )
}

然后我的网络组件无法正常工作。

reactjs web-component jsx documentfragment
1个回答
7
投票

原因是JSX做的工作与<template />标签不同。模板标签的想法是不渲染它的子节点,并且几乎像未解析的文本一样处理它(浏览器实际上解析它只是为了确保其有效的html,但不做任何其他事情)

但是当你在JSX中写这个:

return (
  <template>
    <div>some content</div>
  </template>
)

你基本上是指示反应创建一个'template'元素,然后创建一个'div'元素,然后将这个div作为一个孩子附加到template

所以在幕后发生这种情况:

const template = document.createElement('template')
const div = document.createElement('div')
const text = document.createTextNode('some text')
div.appendChild(text)
template.appendChild(div)

但你想要的是将<template />的内容设置为字符串。你可以使用innerHTML


一个解决方案是:

render() {
  return (
    <template
      dangerouslySetInnerHTML={{
        __html: '<div>some content</div>'
      }}
    />
  )
}

现在你要求做出反应,将所有这些子标签创建为节点元素,但让浏览器决定如何处理它们。

Nicer solution

你可能不想一直使用dangerouslySetInnerHTML。那么让我们创建一个帮助组件:

function Template({ children, ...attrs }) {
  return (
    <template
      {...attrs}
      dangerouslySetInnerHTML={{ __html: children }}
    />
  );
}

现在,只要您需要使用模板,就可以像这样使用它:

render() {
  return (
    <Template>
      {'<div>some content</div>'}
    </Template>
  )
}

不要忘记将内部内容放在引号中,因为它应该是一个字符串。

© www.soinside.com 2019 - 2024. All rights reserved.