![](/img/trans.png)
[英]React.JS How to allow only digits to be typed in input with 'onKeyPress'
[英]Adding text into a text input onKeyPress react.js
我希望在用戶鍵入時將字符串'Surveillance Capitalism'逐個字母輸入到文本輸入(或類似的輸入)中。
該代碼可以正常工作,直到我嘗試將字母添加到輸入中為止,這時我被告知“失敗的道具類型:您為沒有onChange
處理程序的表單字段提供了一個value
道具”。 這種方法可行嗎? 如果不是,什么是好的選擇?
HTML:
<input
id="search-bar"
type="text"
onKeyPress={this.handleKeyPress}
/>
JS:
//Dictates what is typed in the search bar
(https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs)
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
//Converts firstSearchString into an array of its members (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
var searchStringArray = Array.from(firstSearchString);
//Gets contents of search bar
var searchBar = document.getElementById("search-bar").value;
//Length of that content
var i = searchBar.length;
searchBar.value += searchStringArray[i];
};
從本質上講,我想誘使用戶認為他們可以搜索他們想要的任何內容,但是當他們鍵入內容時,我的預設查詢將一個字母一個字母地輸入。
問題是您正在將變量分配給搜索欄:
var searchBar = document.getElementById("search-bar").value;
然后更改變量,以解決您的問題,我只是這樣做:
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
var searchStringArray = Array.from(firstSearchString);
for(let i = 0; i < searchStringArray.length; i++) {
document.getElementById("search-bar").value += searchStringArray[i];
}
};
我認為那是您遇到的麻煩,但是我不確定我是否理解這個問題。 希望這對您有所幫助
嘗試使用onChange事件處理程序,而不是onKeyPress處理程序。 那應該消除您的錯誤。 它們在功能上略有不同,但是應該完成相同的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.