我有以下使用React Native的輸入。
<View style={ styles.container }>
<Input。
placeholder="Add new chat"
value={input}
onChangeText={(text) => setInput(text)}。
leftIcon={
< Icon name="wechat" type="antdesign" size={24} color="black" />
}
/>
<Pressable style={styles. buttonAdd} onPress={createChat}>
<Text style={styles. text}>創建</Text>
</Pressable>/span>
</View>
如果我什么都不輸入,我就會得到我的警報,這很好,但是如果我輸入1或 空格,資料就會被提交。我怎樣才能禁止提交,并在只有空格的情況下設定警報呢?
const [input, setInput] = useState("")。
const createChat = async ( ) => {
if(! input) {
alert("The chat name cannot be blank")。
return;
}
await db
.collection("chats")
.add({
chatName: input
})
.then(() => {
navigation.goBack()。
})
.catch(() => {
alert(錯誤)。
})
};
uj5u.com熱心網友回復:
你可以直接洗掉所有的空格,然后檢查字串是否仍然長于零字符。
例如:
const submit=()=> {
if (input.replaceAll(' ', ' '). length > 0){。
//你的提交邏輯在此。
}
}
否則,你也可以測驗一下重詞,但對于你的需求來說,這可能是多余的。
uj5u.com熱心網友回復:
由于input是一個字串,你可以trim你的字串來洗掉字串兩端的任何空格。
注意trim()將洗掉字串兩端的空白,而不是單詞之間的空格。
const string = " A string with spaces at end" ;
console.log(string.trim())。
const string_with_only_space = " "/span>;
console.log(string_with_only_space.trim()) 。
if(!string_with_only_space.trim()) {
console.log("STRING IS EMPTY") 。
} else {
console.log("STRING IS NOT EMPTY") 。
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
你可以將你的if條件改為
if(! input.trim()) {
alert("The chat name cannot be blank")。
return。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/309134.html
標籤:
