代码之家  ›  专栏  ›  技术社区  ›  bairavand

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

  •  0
  • bairavand  · 技术社区  · 5 年前

    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)

    我只想要下面的标记标签

    let mark = React.createElement('mark', {contenteditable: true}, newNode)
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   The KNVB    5 年前

    我的演示是 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>
      );
    }