简体   繁体   English

React - 如何在没有 jquery 或 innerHTML 的情况下将每个文本字母包装在跨度中

[英]React - How to wrap each letter of text in a span without jquery or innerHTML

I am working with React right now, the javascript code I am trying to duplicate because it doesn't work in React is:我现在正在使用 React,我试图复制的 javascript 代码在 React 中不起作用是:

var textWrapper = document.querySelector('.text');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

What I am currently doing is:我目前正在做的是:

const addSpan = (note: any, styles: any) => {
  return DOMPurify.sanitize(
    note.replace(/\S/g, `<span class='letter' style=${styles}>$&</span>`)
  );
};
<div
      className={classnames('text', classes.aStyle)}
      dangerouslySetInnerHTML={{
        __html: addSpan(myNote, styles)
      }}
/>

This is working fine, but I want another solution in which I don't have to use dangerouslySetInnerHTML because it is unsafe.这工作正常,但我想要另一个解决方案,因为它不安全,我不必使用dangerouslySetInnerHTML的SetInnerHTML。 The problem right now is that my addSpan function successfully wraps each letter with a span, but it's returning a string instead of actual HTML contents that will be interpreted as code.现在的问题是我的addSpan function 成功地用跨度包装了每个字母,但它返回一个字符串而不是实际的 HTML 内容,这些内容将被解释为代码。 That's why I then have to use dangerouslySetInnerHTML so that it sees the string as actual code.这就是为什么我必须使用dangerouslySetInnerHTML以便将字符串视为实际代码的原因。

Is there a way to wrap each letter of a text in a span without using jQuery and dangerouslySetInnerHTML ?有没有办法在不使用 jQuery 和dangerouslySetInnerHTML的情况下将文本的每个字母包装在一个跨度中?

so with React we get the benefit of having JSX.所以有了 React,我们得到了 JSX 带来的好处。 Instead of returning a String, you have the ability to return the element itself in your function.您可以在 function 中返回元素本身,而不是返回字符串。 Below is an example of how to split your string into an array of span's and then how you would call it in your component.下面是如何将字符串拆分为跨度数组以及如何在组件中调用它的示例。

function TestComponent() {

    const addSpan = (note: any, styles: any) => {
     return [...note].map(letter => <span class='letter' style={styles}>{letter}</span>)
    }

    return (
        <div>
            {addSpan("test",{color: 'blue'})}
        </div>
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM