【问题标题】:How to wrap specific text inside a div in a span in react?如何在反应中将特定文本包装在一个跨度的div中?
【发布时间】:2021-06-20 13:09:15
【问题描述】:

我有在里面渲染一些文本的反应组件,但是我如何动态选择一段文本并将其包装在一个跨度中。

代码示例

import { useState } from "react";
import "./styles.css";


export default function App() {

const [text, setText] = useState('Some text will be here but this one will be yellow')


const transformTextCallback = (text,start, end) => {
  let selectedString = text.substring(start, end)
  //how wrapp selectedText into span and return all text where
  //selected text will be wrapped with span
  //exprected result => Some text will <span className='red'>be here but</span> this one will be yellow
}

const onMouseUp = ()=> {
  let data = window.getSelection().getRangeAt(0)
  let start = data.startOffset; //index start select text
  let end = data.endOffset //index end select text

  let transformText = transformTextCallback(text, start, end)
  console.log(transformText)
}


  return (
    <div className="App">
      <div className='textContent' onMouseUp={onMouseUp}>
      {text}
      </div> 
    </div>
  );
}

当我选择文本时,会触发一个函数,该函数接收所选文本的坐标并对其进行处理,所以这就是我将所选文本包装在跨度中并将新文本设置为 setState 的方法,这将是旧的文本包含在 span 中的文本

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您不应该将 JSX 存储在组件的状态中,因此将带有文本的 span 保存到状态并不是最好的方法。它认为这就是你想要做的:

    import { useState } from "react";
    import "./styles.css";
    
    export default function App() {
      const [selected, setSelected] = useState(false);
    
      const text = "Some text that will be wrapped in a span and the color will be yellow";
    
      const handleClick= (e)=> {
        setSelected(!selected);
      }
    
    
      return (
        <div className="App">
          <div className='textContent' onClick={handleClick}>
             {selected ? <span style={{ color: "yellow" }}>
               text 
             </span> : text }         
          </div> 
        </div>
      );
    }
    

    【讨论】:

    • 我需要在选中文本后突出显示文本,所以我应该用选中的新文本替换旧文本 - 突出显示
    • 您是说要更新文本和颜色吗?
    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多