首页 > 解决方案 > 如何在本机反应中将填充物放在我的输入字符串上?

问题描述

这是我想从输入字符串中过滤的单词

badwords: [{name: 'cake'}, {name: 'tea'}, {name: 'pastries'}]

我的搜索功能

searchUpdated() {
const badwords = [{name: 'cake'}, {name: 'tea'}, {name: 'pastries'}];
this.setState({sentence: this.state.review});

const sentence = this.state.review;

const words = sentence.split(' ');

for (let i = 0; i < words.length; i++) {
  if (badwords.map((word) => word.name).includes(words[i])) {
    alert('Sentence contains bard word: ' + words[i]);
  }
}

}

我在这里设置评论值

 <TextInput
          style={[styles.Input, {color: this.state.txt ? 'red' : 'black'}]}
          placeholder="Enter Review"
          // autoCorrect={this.props.autoCorrect}
          autoCapitalize={'none'}
          returnKeyType={'done'}
          keyboardType={'email-address'}
          placeholderTextColor="gray"
          value={this.state.review}
          underlineColorAndroid="transparent"
          onChangeText={(review) => {
            this.setState({review});
          }}
        />

我希望如果我写“我喜欢咖啡,但茶不好”,它会在屏幕上显示警告或其他内容,说明不要在字符串中的任何地方使用单词茶、蛋糕或糕点

标签: javascriptreact-native

解决方案


您可以通过将字符串拆分为单个单词来轻松完成此操作。然后遍历创建的数组并检查每个单词是否等于坏词之一。

这是一个如何完成此操作的简单示例:

const badwords = [{name: 'cake'}, {name: 'tea'}, {name: 'pastries'}];

const sentence = "I like coffee but tea was not good";

const words = sentence.split(' ');

for(let i = 0; i < words.length; i++){
  if(badwords.map(word => word.name).includes(words[i])){
     alert("Sentence contains a bard word: " + words[i]);
  }
}


推荐阅读