我很新ReactJS我只是想做一些小事情,以瞭解更多。ReactJS OnKeyPress觸發按鈕按
我想知道如果OnKeyPress可以觸發按鈕按下。我見過幾個類似的問題,但觸發的只是一個console.log或一個警報。所以我不知道如何觸發按鈕按下。
這是我到目前爲止有:
class Form extends React.Component {
onButtonPress = (e) => {
// this is just an example of what happens when the button is pressed.
this.setState({isClicked: true});
}
keyPress = (event) => {
if (event.key == 'Enter'){
// How would I trigger the button that is in the render? I have this so far.
this.onButtonPress();
}
}
render() {
return (
<div>
<div className="fieldForm">
<input
value={name}
type="name"
onKeyPress={this.keyPress}
/>
</div>
<Button onClick={this.onButtonPress}>Submit</Button>
</div>
)
}
}
請注意,我並沒有包括在這裏的一切,如構造,道具,或者對象屬性的狀態。
這樣做的目的是使它看起來像按鈕已被點擊。當按鈕被點擊時,它會在按鈕上顯示一個小的加載標誌。如果我按下輸入按鈕(按鈕上的加載標誌,這就是爲什麼我要按下按鈕),我想要發生同樣的事情。
這可能嗎?
相當肯定的是,'event.key'值是所有小寫 – Derek