簡體   English   中英

突出顯示句子中的單獨關鍵字

[英]Highlight separate keywords within a sentence

我有兩種狀態,其門店的句子組成的數組,假設說sentencesHard狀態和其他商店的話陣列, criticalWords狀態。 我需要在句子的句子中突出顯示關鍵詞中的那些詞。 現在,如果句子中包含單詞,它會突出顯示整個句子,但我只需要突出顯示該特定單詞而不是整個句子。 例如“ Configuring react-redux 很complicated

現在,我的代碼如下所示:

states={
     criticalWords:["configuring", "complicated"],
     sentencesHard: ["configuring react-redux is complicated"]
}

{this.state.sentencesHard.map((sentence) => (
                <span style={{ backgroundColor: this.state.criticalWords.some(word => sentence.includes(word)) ? '#e4b9b9' : 'initial' }}>
                  {sentence}
                </span>
                ))
              }

在我看來,您的任務比您預期的要復雜一些,因為您需要正確處理句子開頭的大寫關鍵字,而且您很可能希望保留原始標點符號。

因此,對於我假設您使用的基於類的組件(盡管我更喜歡基於函數的組件),您的用例可能看起來像:

 const { render } = ReactDOM const testKeywords = ['configuring', 'complicated'], testSentenses = ['Configuring react-redux, by far, is not complicated, whatsoever.'] class Component extends React.Component { render(){ return ( <div> { this.props.sentenses.map(sentense => { const blocks = sentense.match(/(\\w+|\\W)/g) return blocks.map(block => this.props.keywords.includes(block.toLowerCase()) ? <span style={{backgroundColor: 'grey',color:'white'}}>{block}</span> : block ) }) } </div> ) } } render ( <Component sentenses={testSentenses} keywords={testKeywords} />, document.getElementById('root') )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

您可以將句子拆分為單個單詞:

return (
  <>
    {this.state.sentencesHard.map((sentence) => (
      <span>
        {sentence.split(/(\W+)/g).map((word) => (
          <span style={{ backgroundColor: this.state.criticalWords.some(cw => word.includes(cw)) ? '#e4b9b9' : 'initial' }}>
              {word}
          </span>
        )}
      </span>
    ))}
  </>
)

為句子中的每個單詞添加背景顏色。 像這樣

{
  this.state.sentencesHard.map((sentence) => (
     <span>
      {
       sentence.split(' ').map(word => {
          return this.state.criticalWords.includes(word) ?
                     <span style={{backgroundColor: '#e4b9b9'}}>{word}</span> : word;
       })
      }
     </span>
  ))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM