首页 > 解决方案 > 检测 html 容器中突出显示的文本

问题描述

如何检测用户在非输入/文本区域元素中突出显示的文本?我正在渲染一个跨度内的字符数组,并希望能够检测到用户突出显示了哪些元素。但是,我看不到任何可以让我执行此操作的 ref 属性。

https://codesandbox.io/s/nervous-sound-rk3mf

import React from "react";

const values = ["a", "b", "c", "d", "e"]

const textRef = React.createRef();

export default function App() {
  return (
    <div ref = {textRef}>
      {values.map(val => <var> {val} </var>)}
    </div>
  );
}

标签: htmlreactjs

解决方案


您必须绑定一个单击事件才能突出显示该元素:

import React from "react";

const values = ["a", "b", "c", "d", "e"];

const textRef = React.createRef();

export default function App() {
  // bind this event to the element
  const checkText = e => {
    console.log(`Hilighted item is: "${e.currentTarget.textContent}".`);
  };
  return (
    <div ref={textRef}>
      {values.map((val, i) => (
        <var key={i} onClick={checkText}> //<-----here is the bound event
          {" "}{val}{" "}
        </var>
      ))}
    </div>
  );
}

Codesandbox 已更新。


推荐阅读