大家都知道,dangerouslySetInnerHTML可能会造成XSS攻击,在有UGC业务的情况下,尽量避免使用此属性,所以此时就出现了替代方案,不多bb,先上效果图:
再上代码:
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;