【问题标题】:How to make words inside of text clickable?如何使文本内的单词可点击?
【发布时间】:2020-02-06 00:45:38
【问题描述】:

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

谢谢!!

【问题讨论】:

    标签: javascript reactjs performance text word


    【解决方案1】:

    这是一个 React 解决方案:

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

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

    【讨论】:

      【解决方案2】:

      我认为没有更好的方法来实现上述目的,除了将其转换为数组(例如,使用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>
        );
      }
      

      【讨论】:

        【解决方案3】:

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

        例如,

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

        然后

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

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

        还有更多执行此操作的方法,例如在document 上实现一个点击处理程序,用于测试元素类型。这样一来,所有元素只有一个处理程序,而不是 每个 元素一个处理程序。

        请参阅 MDN 上的 AddEventListener

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-15
          • 1970-01-01
          • 2018-06-03
          • 1970-01-01
          • 1970-01-01
          • 2018-09-23
          相关资源
          最近更新 更多