我如何根据按下的键使用 OnKeypress 来使用我的按钮
How do i use OnKeypress to use my button depending the key pressed
你好,我想根据按下的键重现声音,但我如何传递到我的 onkeypress 中?
我用 howler 重现声音,我使用映射功能为所有按钮重现和创建一个按钮,但我不知道如何将它与 onkeypress 一起使用,就像我希望它在我按下另一个键时改变按钮声音一样w等
//create an array for audioClips
const audioClips = [
{sound : bass, label: "BassDrum"},
{sound : hithat, label: "HitHat"},
{sound : ride, label: "Ride"},
{sound : snare, label: "Snare"},
{sound : splash, label: "Splash"},
{sound : tom, label: "Tom"},
]
class App extends Component {
SoundPlay = (src) => {
const sound = new Howl({
src
});
sound.play();
}
RenderButtonAndSound = () => {
return audioClips.map((soundObj,index) => {
return(
<button key={index}onKeyPress={() => this.SoundPlay(soundObj.sound)} onClick={() =>
this.SoundPlay(soundObj.sound) }>
{soundObj.label}
</button>
)
});
}
render(){
Howler.volume(1.0)
return (
<div className="App">
<h2>
My Virtual Drums
</h2>
{this.RenderButtonAndSound()}
</div>
);
}
}
export default App;
使用 onKeyPress 事件,您可以检查正在输入的键。
const keyboardEvents = (event) =>{
console.log(event.key); // this will return string of key name like 'Enter'
console.log(event.keyCode) //using keycode
if (e.keyCode == 13) { //Press Enter
this.SoundPlay(soundObj.sound)
}
//You can use If-Else or Switch statements to call different sound base on event.key
}
RenderButtonAndSound = () => {
return audioClips.map((soundObj,index) => {
return(
<button key={index} onKeyPress={(e) => this.keyboardEvents(e)} onClick={() =>
this.SoundPlay(soundObj.sound) }>
{soundObj.label}
</button>
)
});
}
你好,我想根据按下的键重现声音,但我如何传递到我的 onkeypress 中? 我用 howler 重现声音,我使用映射功能为所有按钮重现和创建一个按钮,但我不知道如何将它与 onkeypress 一起使用,就像我希望它在我按下另一个键时改变按钮声音一样w等
//create an array for audioClips
const audioClips = [
{sound : bass, label: "BassDrum"},
{sound : hithat, label: "HitHat"},
{sound : ride, label: "Ride"},
{sound : snare, label: "Snare"},
{sound : splash, label: "Splash"},
{sound : tom, label: "Tom"},
]
class App extends Component {
SoundPlay = (src) => {
const sound = new Howl({
src
});
sound.play();
}
RenderButtonAndSound = () => {
return audioClips.map((soundObj,index) => {
return(
<button key={index}onKeyPress={() => this.SoundPlay(soundObj.sound)} onClick={() =>
this.SoundPlay(soundObj.sound) }>
{soundObj.label}
</button>
)
});
}
render(){
Howler.volume(1.0)
return (
<div className="App">
<h2>
My Virtual Drums
</h2>
{this.RenderButtonAndSound()}
</div>
);
}
}
export default App;
使用 onKeyPress 事件,您可以检查正在输入的键。
const keyboardEvents = (event) =>{
console.log(event.key); // this will return string of key name like 'Enter'
console.log(event.keyCode) //using keycode
if (e.keyCode == 13) { //Press Enter
this.SoundPlay(soundObj.sound)
}
//You can use If-Else or Switch statements to call different sound base on event.key
}
RenderButtonAndSound = () => {
return audioClips.map((soundObj,index) => {
return(
<button key={index} onKeyPress={(e) => this.keyboardEvents(e)} onClick={() =>
this.SoundPlay(soundObj.sound) }>
{soundObj.label}
</button>
)
});
}