通过span标签动态包装js字符串,该标签可能会在React中危险地呈现 [英] Dynamically wrap a js string by span tags which can be dangerously rendered in React

查看:47
本文介绍了通过span标签动态包装js字符串,该标签可能会在React中危险地呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我想使用aria标签将单独的span标签添加到字母表中.最终结果将在React中危险地呈现.请指教.这就是我所拥有的.

I have a string and I would like to add span tags to the alphabets alone with an aria-label tag. The end result will be dangerously rendered in React. Please advice. This is what I have.

const str = `D = (C - B) / B`;

const addAriaLabels = (str) => {
  function alphaOnly(a) {
    var b = '';
    for (var i = 0; i < a.length; i++) {
      if (a[i] >= 'A' && a[i] <= 'z') b += a[i];
    }
    return b;
  }
  return alphaOnly(str).split('').map(item => `<span aria-label=\'column ${item}\'>${item}</span>`).join('')
}

console.log(addAriaLabels(str))

预期输出:

< span aria-label ='D列'< D</span>=(< span aria-label ='列C'&C;/span>-< span aria-label ='column B'> B>/span))/< span aria-label ='columnB'&B; B</span>

我不确定如何添加符号本身.

I am not sure on how to add back the symbols itself.

示例:

如果字符串为A,则结果应为< span aria-label =列A"> A</span> .

If string is A, result should be <span aria-label="column A">A</span>.

如果字符串是D =(C-B)/B,则结果应为< span aria-label ='列D'> D</span>=(< span aria-label ='列C'&C;/span>-< span aria-label ='column B'> B>/span))/< span aria-label ='columnB'&B; B</span>

If string is D = (C - B) / B, result should be <span aria-label='column D'>D</span> = (<span aria-label='column C'>C</span> - <span aria-label='column B'>B</span>) / <span aria-label='column B'>B</span>

推荐答案

您不需要 dangerouslySetInnerHTML .

说明:

  • 正则表达式/(([a-z] +)/i )与1个或多个拉丁字母的所有子字符串匹配,不区分大小写.

  • The regex /([a-z]+)/i matches all substrings of 1 or more Latin alphabet letters, case insensitive.

String#split 将捕获的文本包含在结果中的奇数索引处.例如,'baba'.split(/(b)/)为您提供 [","b","a","b",一个] .

String#split with a regex capturing group (/(...)/) includes the captured text in the results at odd-numbered indexes. For example, 'baba'.split(/(b)/) gives you ["", "b", "a", "b", "a"].

一旦获得这些结果,就可以将捕获的奇数索引结果( idx%2 )映射到 span 元素,将偶数映射到 React片段 s.

Once you have these results, you can map the captured, odd-indexed results (idx % 2) to span elements and the even ones to React.Fragments.

addAriaLabels 现在返回一个React组件数组,可以直接在父对象内部呈现.

addAriaLabels now returns an array of React components, which can be rendered directly inside a parent.

const addAriaLabels = str =>
  str.split(/([a-z]+)/i)
    .map((substr, idx) => idx % 2
      ? <span key={idx} aria-label={`column ${substr}`}>{substr}</span>
      : <React.Fragment key={idx}>{substr}</React.Fragment>)

const Parent = () => {
  const str = `D = (C - B) / B`

  return (
    <>
      {addAriaLabels(str)}
    </>
  )
}

这篇关于通过span标签动态包装js字符串,该标签可能会在React中危险地呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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