在jsx对象中插入html标签进行映射 [英] insert html tags inside the jsx object for mapping

查看:171
本文介绍了在jsx对象中插入html标签进行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对象内部有一个带有一些HTML标记的字符串,我想使用map函数在该对象内部打印值.

I have a string inside an object with some HTML tags in it, and I want to print the values inside that object using map function.

const tableBody = [
  {
    date: '02/08/2019',
    item: 'Renewed your <strong>current Team Plan</strong>'
  },
  {
    date: '05/09/2019',
    item: 'Renewed your current Team Plan 2'
  },
  {
    date: '15/10/2019',
    item: 'Renewed and upgraded to the <strong> Business Plan </strong> with 3 new members'
  }
];


<table>
{tableBody.map(tableBody => (
  <tr>
   <td>{tableBody.date}</td>
   <td>{tableBody.item}</td>
  </tr>
))}
</table>

当我运行此代码时,我希望字符串内的<strong>标签被编译为HTML元素,而不是呈现为纯文本.那么有什么办法可以实现这个目标呢?

when I run this code, I want that <strong> tag inside the string compiled as an HTML element instead of rendered as plain text. So is there any way to achieve this guys?

推荐答案

您应渲染ReactElement或使用 dangerouslySetInnerHTML

You should render ReactElement or use dangerouslySetInnerHTML

const tableBody = [
  {
    date: '02/08/2019',
    item: (
//    v <React.Fragment>
      <>
        Renewed your <strong>current Team Plan</strong>
      </>
    )
  }
];


export default function App() {
  return (
    <FlexBox>
      <table>
//                      v Notice the shadowing in OP's code
        {tableBody.map(tableBody => (
          <tr>
            <td>{tableBody.date}</td>
//                v ReactElement
            <td>{tableBody.item}</td>
          </tr>
        ))}
      </table>

//    v `dangerouslySetInnerHTML` example
      <table>
        <tr>
          <td>{'02/08/2019'}</td>
          <td
            dangerouslySetInnerHTML={{
//                      v A string, exposed to attacks, not recommended
              __html: 'Renewed your <strong>current Team Plan</strong>'
            }}
          />
        </tr>
      </table>
    </FlexBox>
  );
}

游乐场:

这篇关于在jsx对象中插入html标签进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆