如何使文本中的单词可点击?

How to make words inside of text clickable?

我正在寻找一种使文本中的单词可点击的解决方案,我考虑过将文本拆分为单词数组并为每个单词创建一个 btn...但此解决方案性能不佳...有人有什么想法吗?文字是:

const paragraph = 'Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence; and had lived nearly twenty-one years in the world with very little to distress or vex her.'

谢谢!!

假设您想将这些词放在 html 页面中,最好的办法是将每个词包装在 <span> 元素中并将点击处理程序附加到 <span> .

例如,

<span>Emma</span> <span>Woodhouse</span>...

然后是

Array.from(document.querySelectorAll('span')).forEach(span => {
 span.addEventListener('click', ...)
})

当然,使用 React 或其他框架或库可能会有不同的首选方式。

还有更高效的方法来实现这一点,例如在 document 上实现一个点击处理程序来测试元素类型。这样一来,所有元素只有一个处理程序,而不是 每个 元素只有一个处理程序。

参见 MDNAddEventListener

这是一个 React 解决方案:

function clickableWords(paragraph, clickCallback) {
  const words = paragraph.split(/ /g);
  return words.map(w => 
    <span onClick={() => clickCallback(w)}>{w}</span>
  );
}

当单词被点击时,clickCallback将以单词作为参数被调用。

我认为没有更好的方法来实现上述目标,除了将其转换为数组(例如,使用 Array.from())、遍历句子并将每个字符呈现为可单独点击元素。

export function App() {
  const paragraph = 'Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence; and had lived nearly twenty-one years in the world with very little to distress or vex her.';

  const handleClick = (word) => {
    console.log(word);
    // handle the rest

  };

  const renderParagraph = () => Array.from(paragraph)
    .map((word) => <span onClick={() => handleClick(word)}>{word}</span>);

  return (
    <div className="App">
      {renderParagraph()}
    </div>
  );
}