简体   繁体   English

在ReactJS中更新onkeypress输入中的值

[英]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. 我一直在尝试获取如何使用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. 我还具有另一个验证功能,因此keypress功能仍将通过验证功能。 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 "." 我只是不知道将其放置在cos中的正确位置,因为它显示语法错误:意外的标记,指向“。” between "window" and "onkeypress" 在“窗口”和“ 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... 您可以通过javascript引用元素来分配焦点,例如...

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

OK here it is... I called the window.onkeydown function outside the class as it doesn't update any state. 好的,这里是...我在类外调用了window.onkeydown函数,因为它不更新任何状态。 And I later realised that window.onkeydown targets and add the values in the input 后来我意识到window.onkeydown定位并在输入中添加值

import ... from ...;

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

class App extends ... {
    ...
 }

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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