简体   繁体   中英

Update values in input onkeypress in ReactJS

I have been trying to get how to update an input based on keypress in window with ReactJS. I'm building a basic calculator, and it has only one input. I want the input to always be targeted once a key is pressed and also update the values. I also have another function for validation, so the keypress function will still pass through the validation function. Thank you!

I have something like this:

window.onkeypress = function(e){
    this.inputFocus(); //my custom function to position the cursor in the input
    this.setState({display: this.state.display + e.key});
}

I just don't know the proper location to fit it in cos it says syntax error: unexpected token, pointing at the "." between "window" and "onkeypress"

If you have focus on the input field, by pressing a button, it should enter the value into that input field, and so all you should need to do is make your input a controlled component by doing the following

export default class YourClass extends Component {
    constructor(props) {
        super(props);
        this.state = {
            numberValue: 0
        }
    }
    updateValue = (numberValue) => {
        this.setState({numberValue})
    }
    render() {
        return (
            <input 
                type='number'
                value={this.state.numberValue} // this is initialized in this.state inside the constructor
                onChange={(input) => this.updateValue(input.target.value)}
            />
        )
    }
}

So whenever you change the value, it will automatically update the state, which then sets the value of your input. This is all predicated on you having focus on that input though, so make sure it has focus.

You can assign focus by referencing the element through javascript like...

document.getElementById('yourElement').focus()

OK here it is... I called the window.onkeydown function outside the class as it doesn't update any state. And I later realised that window.onkeydown targets and add the values in the input

import ... from ...;

window.onkeydown = function(e) {
    input.focus()
}

class App extends ... {
    ...
 }

export default App;

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