如何在 React JS 中创建类似于 Javascript 的节点?

我只是使用 contenteditable 构建了一个拼写检查器功能。每当用户 keyup 时,它都会被触发。错误的单词将被标记标签包裹。我刚刚使用了 javascript,但我需要以 React 的方式来做。

let originalNode = document.createElement('p')
let textNode = document.createTextNode('Sri Lankan Tamil activists in Britain paid tribute to the victims of the Sri Lankan civil war on Friday by placing the national flower of Tamil')
originalNode.appendChild(textNode)
let str = 'Tamil'
let wholeWordRegExp = new RegExp('\\b' + str + '\\b')
let pos = textNode.nodeValue.search(wholeWordRegExp)
let newNode = textNode.splitText(pos)
let mark = document.createElement('mark')
mark.setattribute("contenteditable",true)
textNode.parentNode.insertBefore(mark,newNode)
newNode.splitText(str.length)
mark.appendChild(newNode)
console.log(originalNode)
//console.log(originalNode.firstChild)

我只想要 React 中的标记标签,如下所示

let mark = React.createElement('mark',{contenteditable: true},newNode)
pengsijing 回答:如何在 React JS 中创建类似于 Javascript 的节点?

我的演示是 here

  import React,{ useState } from 'react';
  export default function Test(props) {
  const orgText="Sri Lankan Tamil activists in Britain paid tribute to the victims of the Sri Lankan civil war on Friday by placing the national flower of Tamil";
  const [textHTML,setTextHTML]=useState([orgText]);
  let handleChange = e => {
    
    let str=e.target.value.trim();
    let wholeWordRegExp = new RegExp('\\b' + str + '\\b')
    let pos=orgText.search(wholeWordRegExp)
    let temp=[];
    if (pos>-1){
      temp.push(orgText.substring(0,pos));
      temp.push(
        <mark
          key="gg"
          contentEditable={true}
          suppressContentEditableWarning={true}>
            {str}
        </mark>    
      )
      temp.push(orgText.substring(pos+str.length));
      setTextHTML(temp);
    }
  };
  return (
    <form>
      <p>
        {textHTML}
      </p>
      <input type="text" onChange={handleChange} />
    </form>
  );
}
本文链接:https://www.f2er.com/50484.html

大家都在问