所以我希望我的react 代码能够检测到我输入的每个链接,例如"http://localhost:3000/" 它为我提供了一个格式化的链接,而不是纯文本
以下是我的代码:
//Linkify.jsx
import DOMPurify from 'dompurify'
const Linkify = ({ children }) => {
const isUrl = (word) => {
const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
return word.match(urlPattern);
};
const addMarkup = (word) => {
return isUrl(word) ? `<a class="text-blue-500 hover:text-blue-600 transition" href="${word}">${word}</a>` : `<span className="no-underline">${word}</span>`;
};
const words = children.split(" ");
const formatedWords = words.map((w, i) => addMarkup(w));
const html = DOMPurify.sanitize(formatedWords.join(' '))
return <span dangerouslySetInnerHTML={{ __html: html }} />;
};
export default Linkify;
import Linkify from "./Linkify"
const Test = () => {
return (
<div>
<Linkify>
http://localhost:3000/
</Linkify>
</div>
)
}
export default Test
//this code gives me not a link but a plain text
任何有用的东西