react 搜索關鍵詞高亮dangerouslySetInnerHTML的替代方案

你們都知道,dangerouslySetInnerHTML可能會形成XSS攻擊,在有UGC業務的狀況下,儘可能避免使用此屬性,因此此時就出現了替代方案。html

很少bb,先上效果圖react

1.gif

再上代碼markdown

import React, { useState } from "react";

const App = () => {
  const [search, setSearch] = useState("");
  const data = [
    { id: 75, name: "研發部-其餘" },
    { id: 154, name: "摸魚" },
    { id: 14, name: "12343" },
  ];
  const renderName = (name) => {
    if (search.length && name.indexOf(search) > -1 && search !== name) {
      const temp = name.split(search);
      const dom = [];
      for (let i = 0; i < temp.length - 0.5; i += 0.5) {
        if (Math.floor(i) !== i) {
          dom.push(
            <span key={i} style={{ color: "red" }}>
              {search}
            </span>
          );
        } else if (temp[i].length) {
          dom.push(<span key={i}>{temp[i]}</span>);
        }
      }
      return dom;
    } else {
      return (
        <span style={{ color: search === name ? "red" : null }}>{name}</span>
      );
    }
  };
  return (
    <div>
      <input onChange={(e) => setSearch(e.target.value)} />
      <ul>
        {data.map((item) => (
          <li key={item.id}>{renderName(item.name)}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;
複製代碼
相關文章
相關標籤/搜索