我有這個代碼:
import React, { Component } from "react";
export default class Safe extends Component {
constructor(props) {
super(props);
this.state = {
userInput: "",
password: 1234
}
}
keyClicked = (evt) => {
// HERE!!
}
render() {
return (
<div className="safe">
<div className="display">{this.state.userInput}</div>
<div className="keypad">
{Array.from({length: 9}, (x, key) => <button className="key" key={key } onClick={this.keyClicked}>{key }</button>)}
</div>
</div>
)
}
}
我正在嘗試用數字鍵盤制作“安全”。為了打開保險箱,用戶必須輸入特定密碼才能“打開它”。
目前,我正在努力將用戶通過數字鍵盤輸入的內容顯示到顯示屏上。但是,我不確定如何獲取用戶通過數字鍵盤輸入的數字。我已經發表評論說“這里!!” 顯示我想在哪里訪問輸入的號碼。
我曾嘗試使用evt.target.value,但當我嘗試使用console.log()時evt,它顯示為空字串。
感謝任何幫助,因為我是 React 新手!
uj5u.com熱心網友回復:
我認為對于這種情況,最好使用map(). 并事先宣告陣列。這樣就可以將點擊的數字作為引數傳遞給點擊處理程式。
嘗試以下操作:
export default class Safe extends Component {
constructor(props) {
super(props);
this.state = {
userInput: "",
password: 1234
};
}
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
handleClick = (n) => {
console.log(n);
};
render() {
return (
<div className="safe">
<div className="display">{this.state.userInput}</div>
<div className="keypad">
{this.numbers.map((number, i) => {
return (
<button
className="key"
key={i}
onClick={() => this.handleClick(number)}
>
{number}
</button>
);
})}
</div>
</div>
);
}
}
uj5u.com熱心網友回復:
是的,你可以通過這種方式得到這個
import React, { Component } from "react";
export default class Safe extends Component {
constructor(props) {
super(props);
this.state = {
userInput: "",
password: 1234
}
}
keyClicked = (evt) => {
console.log(evt)
}
render() {
return (
<div className="safe">
<div className="display">{this.state.userInput}</div>
<div className="keypad">
{Array.from({length: 9}, (x, key) => <button className="key" key={key } onClick={()=>this.keyClicked(key )}>{key }</button>)}
</div>
</div>
)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420418.html
標籤:
