简体   繁体   中英

Adding text into a text input onKeyPress react.js

I want the string 'Surveillance Capitalism' to be inputted letter by letter into a text input (or something that looks like one) as a user types.

The code works up to the point I try to add the letter into the input, at which point I am told 'Failed prop type: You provided a value prop to a form field without an onChange handler'. Is this method possible? If not what is a good alternative?

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];
  };

Essentially I want to trick the user into thinking they can search whatever they want but when they go to type, my preset query will be entered letter by letter.

The problem is that you are assigning a variable to the search bar:

var searchBar = document.getElementById("search-bar").value;

then altering the variable, to fix your problem i just did this:

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];
        }
  };

I think that's what you were having trouble with but i'm not sure if i understood the question. I hope this helped

Try the onChange event handler, rather than the onKeyPress handler. That should remove the error you have. They are functionally slightly different, but should accomplish the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM