gpt4 book ai didi

javascript - 如何根据句子索引突出显示句子?

转载 作者:行者123 更新时间:2023-12-01 00:09:31 24 4
gpt4 key购买 nike

我有一个文本编辑器,用户可以在其中输入一些文本/段落,并在单击“提交”时调用 API。后端将整个段落分割成句子,并在响应中以数组形式发送它们。现在我将句子数组存储到一个状态中,然后使用 map() 函数显示它,我还将“硬”对象存储到一个 HardIndex 状态中。我必须突出显示索引处于 HardIndex 状态的句子,在我的示例中,需要突出显示响应“0”和“2nd”句子,但我无法做到这一点。有人可以告诉我如何突出显示那些索引处于“hardIndex”状态的句子吗?

API 发送如下响应:

{
"sentences": [
"The computer runs on a three-step cycle namely input, process, and output.",
"Also, the computer follows this cycle in every process it was asked to do. ",
"In simple words, the process can be explained in this way. ",
],
"hard": [
0,
2
] //index of sentences which needs to be highlighted

到目前为止我已经写了他的

states={
hard:[],
sentencesHard: []
}


performSentenceAnalysis = async () => {
const { enteredText } = this.state;

const body = { snippetdesc: enteredText };
const stringifiedBody = JSON.stringify(body);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: stringifiedBody
};
const url = "http://localhost:8000/api/readability";
try {
const response = await fetch(url, options);
const result = await response.json();

this.setState(prevState => ({
sentencesHard: result.sentences,
hardIndex: result.hard,
}));
} catch (error) {
console.error(error);
}
};


//the sentences array is displayed here and I need to highlight those sentences whose indexes are in the hard array

<div className="lastBox">
{ this.state.sentencesHard.map(sentence =>{
return(
<div>
{sentence}
</div>
)
}
</div>

最佳答案

您可以使用条件运算符并查看要迭代的字符串的索引是否包含在 hard 数组中:

<div className="lastBox"> {
this.state.sentencesHard.map((sentence, i) => (
<div style={{ backgroundColor: this.state.hardIndex.includes(i) ? 'yellow' : 'initial' }}>
{sentence}
</div>
))
} </div>

(如果你有很多句子,你可以预先将数组转换为 Set,以将计算复杂度从 O(n ^ 2) 降低到 O(n))

您的状态属性名称有点令人困惑。您当前的 hardIndex 实际上是一个数组,而不是索引,并且您的 sentencesHard 中只有一些实际上是困难的(hardIndex 的索引)。也许可以考虑将状态属性更改为 API 返回的内容:

this.setState(() => result);

然后引用sentenceshard属性。 (或者可以将 hard 属性重命名为 hardIndicies,以使其更清楚它的实际含义)

关于javascript - 如何根据句子索引突出显示句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164045/

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