繁体   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