gpt4 book ai didi

javascript - 使用 JavaScript 突出显示字符串中单词的数据结构

转载 作者:太空狗 更新时间:2023-10-29 16:48:06 25 4
gpt4 key购买 nike

我有一个字符串

const string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tristique elit in volutpat iaculis. Proin a tincidunt turpis, et condimentum libero. Duis convallis nulla eu mattis porta. Nulla facilisi. Proin nec viverra orci. Nunc aliquam enim orci, ut dictum ipsum auctor ut. Quisque consectetur vestibulum tortor, mollis hendrerit velit hendrerit vel. In hac habitasse platea dictumst. Morbi volutpat lectus purus, eu sagittis odio viverra in. Phasellus vel volutpat felis. Proin a metus sit amet ipsum congue faucibus nec faucibus nisl. Aenean eu nisl ac velit dapibus vulputate non efficitur urna. Phasellus laoreet suscipit dictum. Curabitur sit amet justo at nisi dictum dapibus."

我希望能够突出显示一些连贯的单词序列,并在将鼠标悬停在单词上时显示工具提示。

数据结构会为此寻找什么?

我猜应该是这样的

id, wordIndexStart, wordIndexEnd, note
=======================================
1, 0, 5, Some note

为了突出前 6 个词,给我类似的东西

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tristique elit in volutpat iaculis (...)

但是我如何在 React 或类似的东西中返回这个带有突出显示文本的字符串?

通常,我会打印我的文字

<p>{string}</p>

但我想应该是这样的

<p>{string.split(" ").map(word => <span>{word}).join(" ")</p>

但是我该如何创建 <span>例如,围绕前 6 个词?

最佳答案

这个怎么样:

const rules = {
start: 0,
end: 5,
tooltip: "Some note"
};
const Highlight = ({ words }) => {
const portion = words.split(" ").slice(rules.start, rules.end).join(" ");
const rest = words.split(" ").slice(rules.end).join(" ");

return (
<span>
<span className="highlight">{portion}</span>
<span className="standard">{rest}</span>
</span>
);
};
const App = () => {
const sentence = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tristique elit in volutpat iaculis.';

return (
<div>
<Highlight words={sentence} />
</div>
)}
;

ReactDOM.render(<App />, document.getElementById("root"));
.highlight {
font-weight: bold;
color: red;
}

.standard {
color: grey;
}
  <div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

关于javascript - 使用 JavaScript 突出显示字符串中单词的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48894108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com