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

标签 javascript reactjs

我有一个文本编辑器,用户可以在其中输入一些文本/段落,并在单击“提交”时调用 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/

相关文章:

javascript - JS : Fetch string from array that matches line in form-input

javascript - RequireJS 错误回调 (errback) 未被调用

PHP AJAX文件上传解决方案

reactjs - 使用本地存储在页面加载时响应重定向

javascript - (JavaScript) 获取数组中交替值的总和并从中获取最大值

javascript - Ajax响应不带数据

javascript - 即使条件不满足,if 条件也会被执行

javascript - React组件渲染数据两次

reactjs - Material-UI slider - 使用比例更改值

reactjs - 从react.js源代码生成序列图的工具