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



我正在寻找一种使文本中的单词可点击的解决方案,我想过将文本拆分为单词数组并为每个单词创建一个 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.'

谢谢!!

这是一个 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>
);
}

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

例如,

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

然后

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

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

还有更多性能方法可以实现这一点,例如在测试元素类型的document上实现单击处理程序。 这样,所有元素只有一个处理程序,而不是每个元素都有一个处理程序。

请参阅 MDN 上的 AddEventListener

最新更新