在我目前在ReactJS的作业中,我被要求呈现一个包含url地址的字符串,因此这些url将是可点击的链接,并且文本将通过搜索词突出显示。
因此,我制作了一个导入"react-linkify“和"react-highlight-words”组件的组件。
如果我单独使用组件,那么url地址将被转换为可点击的链接。因此,对于作为自己的组件,文本将按预期通过搜索词突出显示。
当我同时使用它们时,组件功能可以工作,但组件不会将urls呈现给链接。
我已经尝试了在Google中搜索的每一个解决方案,甚至使用正则表达式使我自己的链接具体化,但链接仍然是一个字符串,而不是可点击的链接。
我的CodeSandBox.io代码如下:
import React from "react";
import ReactDOM from "react-dom";
import Linkify from "react-linkify";
import Highlighter from "react-highlight-words";
import "./styles.css";
function App() {
let text =
"Hello CodeSandbox. Start editing to see some magic happen! Click to see this video: https://www.youtube.com/watch?v=VMcPWuQ7IeE ";
return (
<div className="App">
<Linkify>
<Highlighter
highlightClassName="YourHighlightClass"
searchWords={["magic", "video"]}
autoEscape={true}
textToHighlight={text}
/>
</Linkify>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);我是React的新手,如果你能在这个问题上帮助我,我将不胜感激。
发布于 2020-01-04 07:18:04
你可以改进它,但我只是设法让它以这种方式工作: 1.在荧光笔的searchWords数组中添加"http“。2.使用findChunks选择从开始到下一个空格字符的完整单词。例如,任何像'https://codesandbox.io/s/k20x3ox31o‘这样的url都会完全高亮显示。3.使用自定义highlightTag在Linkify中包装突出显示的单词。
const findChunks = ({
autoEscape,
caseSensitive,
sanitize,
searchWords,
textToHighlight
}) => {
const chunks = [];
const textLow = textToHighlight.toLowerCase();
const sep = /[\s]+/;
const singleTextWords = textLow.split(sep);
let fromIndex = 0;
const singleTextWordsWithPos = singleTextWords.map(s => {
const indexInWord = textLow.indexOf(s, fromIndex);
fromIndex = indexInWord;
return {
word: s,
index: indexInWord
};
});
searchWords.forEach(sw => {
const swLow = sw.toLowerCase();
singleTextWordsWithPos.forEach(s => {
if (s.word.includes(swLow)) {
const start = s.index;
const end = s.index + s.word.length;
chunks.push({
start,
end
});
}
});
});
return chunks;
};
/******************************************************/
<Highlighter
highlightClassName="YourHighlightClass"
textToHighlight={message.text}
searchWords={['http']}
autoEscape={true}
findChunks={findChunks}
highlightTag={({ children, highlightIndex }) => (
<Linkify><span style={{backgroundColor: 'crimson', color: 'white'}}>{children}</span></Linkify>
)}/>
https://stackoverflow.com/questions/59549316
复制相似问题