在 jsx 对象中插入 html 标签进行映射

IT技术 javascript reactjs jsx
2021-05-26 17:39:10

我在一个对象中有一个字符串,其中包含一些 HTML 标签,我想使用 map 函数打印该对象内的值。

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 元素,而不是呈现为纯文本。那么有没有办法实现这些家伙?

4个回答

你应该渲染ReactElement或使用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>
  );
}

操场:

编辑 Q-57955460-ReactElementRender

你需要安装 html react parser pacakge

npm install react-html-parser

这是你的答案:-

import ReactHtmlParser from 'react-html-parser';

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>
  <tbody>
{tableBody.map((tableBody,i) => (
  <tr key={i}>
   <td>{tableBody.date}</td>
   <td>{ReactHtmlParser(tableBody.item)}</td>
  </tr>
))}
</tbody>
</table>

您可以使用,dangerouslySetInnerHTML但这不是一个好习惯。您可以在插入之前查找清理 HTML 的方法,dangerouslySetInnerHTML或者您可以更改 json 结构(如果可能和/或可行)

将您的项目拆分为另一个对象,例如:

item : { 
   first: ' some text ', 
   second: 'the strong text', 
   third :' the other text' 
} 

然后在 JSX 中

<td>{tableBody.item.first} <strong>{tableBody.item.second}</strong> {tableBody.item.third}</td>

首先,您不应该将您在 map func 中访问的变量命名为与您正在运行 map 的变量相同的名称

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

应该是这样的

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