index.jsx 1.1 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import React from 'react';

function highlightText(originalText, keyword) {
  const regex = new RegExp(`(${keyword})`, 'gi');
  return originalText.replace(regex, "<span style='color:#ff4800'>$1</span>");
}

function Highlighter({ children, keyword }) {
  const html = keyword ? highlightText(children, keyword) : children;

  const handleClick = (e) => {
    console.log('====================================');
    console.log(e.target.src);
    console.log('====================================');
    console.log('====================================');
    console.log(e);
    console.log('====================================');
  };

  if (typeof children === 'string') {
    return (
      <div onClick={handleClick} className="limit" dangerouslySetInnerHTML={{ __html: html }} />
    );
  }

  const clonedChildren = React.Children.map(children, (child) => {
    if (typeof child === 'string') {
      return (
        <div onClick={handleClick} className="limit" dangerouslySetInnerHTML={{ __html: html }} />
      );
    }
    return child;
  });

  return <div>{clonedChildren}</div>;
}

export default Highlighter;