【问题标题】:use HTML tags in JS variable (react)在 JS 变量中使用 HTML 标签(反应)
【发布时间】:2020-09-03 06:29:36
【问题描述】:

我正在尝试查看某个用户是否在帖子中被提及。如果是这样,我想将用户名链接到个人资料。

我尝试了什么:

  if (mentions.length === 1) {
    const splitSearch = '@' + mentions[0].user.name;
    const replaceWith =
      '<a href=profile/' +
      mentions[0].user._id +
      '>@' +
      mentions[0].user.name +
      '</a>';
    newText = text.split(splitSearch).join(replaceWith);

  }

...

return (
...
{mentions.length > 0 && (
  <p id='text-container'>{newText}</p>
)}

但我只是将标签作为纯文本返回:

hi <a href=profile/5f1bd6c7d90cb03e845adbbf>@user1</a>. 
hello <a href=profile/5f30380288a63e001755401e>@user2</a>.

我是否需要以另一种方式编写replaceWith const?我尝试了Link 而不是a,但无法正常工作。

提前致谢!

【问题讨论】:

    标签: html reactjs tags


    【解决方案1】:

    React 只能渲染 JSX 组件。

    构造一个子元素数组,而不是构造一个HTML字符串。找到提及时,将 &lt;a&gt;(一个 JSX 元素,而不是字符串)放入其相邻子元素之间的数组中:

    const children = text.split(splitSearch);
    // Insert an `<a>` between each element:
    for (let i = children.length - 1; i > 0; i--) {
      const a = <a href={`profile/${mentions[0].user._id}`}>@{mentions[0].user.name}</a>;
      children.splice(i, 0, a);
    }
    
    // Then render:
    {mentions.length > 0 && (
      <p id='text-container'>{children}</p>
    )}
    

    【讨论】:

    • 感谢您的回答。我有几个问题。为什么使用“children.length - 2”?如果有人键入“hi @user1”,那将是 0,不是吗?我尝试了有和没有-2。两次拼接后我都得到一个空数组。
    • 我仍然无法真正让它工作。当我在拼接后记录“孩子”时,我有一个数组。所以这行得通。但是 {children} 是空的。由于拼接是在 if 语句中,所以我需要在此之前说“让孩子 = []”之类的话,对吧?
    • 一旦你生成了 children 数组,你需要以某种方式将它放到渲染部分 - 无论是通过重新分配 children 还是其他方式
    • 它有效。多谢。你知道我如何通过提及来映射吗?那么是不是提到了不止一个用户,每个用户都有一个a-tag?
    • 您可以使用.match 而不是.split - 匹配任何提及的内容,或匹配任何未提及的内容,将它们分开,然后在阵列上使用.map 将所有提到&lt;a&gt;s。
    【解决方案2】:

    错了。

    react 的想法不是“像您的示例那样生成自己的 html”。

    您应该在 return 中使用 map(并为数组中的每个项目生成 Link),如下所示:

    return (
        {
            mentions.length > 0 && (
                <p id='text-container'>
                    {
                        mentions.map((m) => (
                           <Link key={m.user._id} to=`${m.user._id}`>
                             {m.user.name}
                           </Link>
                        ))
                    }
                </p>
            )
        }
    )
    

    【讨论】:

    • 这个问题:提及在文本中。例如“你好@user1,我想告诉你什么......”。当我简单地映射提及时,我将无法仅链接用户名,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2021-03-14
    相关资源
    最近更新 更多