簡體   English   中英

如何將從 object 的數組中獲取的一部分文本包裝在 span 標記中?

[英]How to wrap a part of text fetched from array of object in a span tag?

給定 json object 如下:

const data = [
  {
    id: "text1",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin odio a luctus ornare. Pellentesque nisl tis tellus nec, dapibus turpis. In hac habitasse platea vitae.",
  },
];

如果我想包含在<span>標簽內獲取的部分文本,例如:

<p>Lorem ipsum <span>dolor sit amet</span>. </p>

我該怎么做呢?

根據您的評論,我想您知道應該將哪些文本放在 span 下

const data = [
  {
    id: "text1",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin odio a luctus ornare. Pellentesque nisl tis tellus nec, dapibus turpis. In hac habitasse platea vitae.",
  },
];

const textToSpan = 'dolor sit amet';

在這種情況下,您可以拆分字符串並使用如下內容進行渲染:

const aText = data.text.split(textToSpan);

const aTextRender = aText.reduce((result, t) => {
  if (result.length) {
    result.push(<span>{textToSpan}<span>);
  }
  result.push(t);
  return result;
}, [])

return (
  <p>
    {aTextRender}
  <p>
);

代碼雖然沒有測試:o

這應該做你的工作!

    data[0].text.replace("dolor sit amet", "<span>dolor sit amet</span>");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM