当用户输入某些内容时,如何设置自定义输入状态结构js

时间:2017-12-02 07:19:06

标签: javascript reactjs input redux

我是React js.的新手。当用户输入一个单词并按下空格键时,我想这样做,它将在数组中保存为新单词,输入框中的值将被清除。 enter image description here

代码

  state = {

        showThisValue:"", 
        storeValue:[] // ["Walk","on","th"]

    };


  handleInput = e => {

        /* Store the value I have no Idea how to do this */

        if(e.target.value === " "){




        }else {

                      let updatedValue = this.state.storeValue.length === 0 ? this.state.storeValue.concat(e.target.value) : this.state.storeValue.slice(this.state.storeValue.length - 1).concat(this.state.storeValue[this.state.storeValue.length - 1].concat(e.target.value))

  this.setState({
          storeValue:updatedValue
   })


        }



    };

逻辑

   let updatedValue = this.state.storeValue.length === 0 ? this.state.storeValue.concat(e.target.value) : this.state.storeValue.slice(this.state.storeValue.length - 1).concat(this.state.storeValue[this.state.storeValue.length - 1].concat(e.target.value))

但是上面的代码会像个人信件一样返回这样的东西

["w","a","l","k"]

1 个答案:

答案 0 :(得分:1)

希望这是你想要的!

li
var input = document.querySelector('input');
var p = document.querySelector('p');
var content = p.innerText.split(' ');
var editIndex = 0;
var text = '';

input.addEventListener('keydown', function(e){
    if(e.which === 8){ // Backspace
        text = text.slice(0, text.length - 1); // delete 1 character.
    }else if(e.which === 32){ // Spacebar
        changeText();
    }else{
        text += e.key;
    }
    console.log(text); console.log(e.which);
});

function changeText(){
    content[editIndex] = text;
    p.innerText = content.join(' ');
    
    editIndex++;
    text = '';
    input.value = '';
}