[英]How can i put fillter on my input string in react native?
這是我想從輸入字符串中過濾的單詞
badwords: [{name: 'cake'}, {name: 'tea'}, {name: 'pastries'}]
我的搜索 function
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});
}}
/>
我希望如果我寫“我喜歡咖啡,但茶不好”,它會在屏幕上顯示警告或其他內容,說明不要在字符串中的任何地方使用單詞茶、蛋糕或糕點
您可以通過將字符串拆分為單個單詞來輕松完成此操作。 然后遍歷創建的數組並檢查每個單詞是否等於壞詞之一。
這是一個如何完成此操作的簡單示例:
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]); } }
對於 react-native 中的 TextInput,您可以在onChangeText
屬性中跟蹤您的壞詞。 例如,
<TextInput value={yourInputValue} onChangeText={this.onChangeText} />
然后在onChangeText
function 中,可以使用 javascript 的includes
onChangeText = (text) => {
badwords.map(word=>{
if(text.includes(word.name)) {
// the text contains word in badwords
console.log("Show your alert",word);
} else {
this.setState({review: word});
}
})
}
快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.