簡體   English   中英

在ReactJS中更新onkeypress輸入中的值

[英]Update values in input onkeypress in ReactJS

我一直在嘗試獲取如何使用ReactJS在窗口中基於按鍵更新輸入。 我正在構建一個基本的計算器,它只有一個輸入。 我希望輸入總是在按下某個鍵后成為目標,並且還要更新值。 我還具有另一個驗證功能,因此keypress功能仍將通過驗證功能。 謝謝!

我有這樣的事情:

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

我只是不知道將其放置在cos中的正確位置,因為它顯示語法錯誤:意外的標記,指向“。” 在“窗口”和“ onkeypress”之間

如果您專注於輸入字段,則可以通過按按鈕將值輸入到該輸入字段中,因此,您需要做的就是通過執行以下操作使輸入成為受控組件

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)}
            />
        )
    }
}

因此,無論何時更改值,它都會自動更新狀態,然后設置輸入的值。 所有這些都取決於您是否專注於該輸入,因此請確保它具有焦點。

您可以通過javascript引用元素來分配焦點,例如...

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

好的,這里是...我在類外調用了window.onkeydown函數,因為它不更新任何狀態。 后來我意識到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