简体   繁体   English

检测在 React 的段落中点击了哪个单词

[英]Detect which word is clicked within a paragraph in React

I have a paragraph with some text that I am showing to a user.我有一个段落,其中包含一些要显示给用户的文本。 How do I detect the word that the user clicks on within the paragraph?如何检测用户在段落中点击的单词? For example, if a user clicks 'green' on a page, how could I detect that they specifically clicked on 'green'?例如,如果用户点击页面上的“绿色”,我如何检测到他们专门点击了“绿色”?

const str = 'The sky is blue. The grass is green. The stop sign is red.'

const handleClick = () => {
  alert(e.target.value);
}

const Content = () => {
  return (
    <div>
      <p onClick={handleClick()}>{str}</p>
    </div>
  );
};

Something like this...像这样的东西...

const str = 'The sky is blue. The grass is green. The stop sign is red.'

const handleClick = (s) => {
    alert(s);
}

return (
    <div>
        {
            str.split(' ').map(s => {
                return <span onClick={() => handleClick(s)}>{s}&nbsp;</span>
            })
        }
    </div>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM