Apply button 'Active' styles on keypress in React

女生的网名这么多〃 提交于 2020-06-12 07:33:29

问题


I have a drum app in React/Redux that's fully functional as it stands, but I want to be able to apply the active button style when the corresponding keypress is made just like it does when I physically click the button. As it stands, clicking the button does a transition but typing the corresponding key just plays the audio file, and isn't really linked to the button. Is there a way to mark the corresponding button active on keypress?

Heres my CodeSandbox: https://codesandbox.io/s/k29r3928z7


回答1:


This is a perfect use case to use ref (as the documentation says, do not abuse its use).

For each button, you need a "ref"(erence) to the DOM element. When you press a key and you find its code in your json, you will access the corresponding reference to the button and trigger the "focus" method, to indicate the UI that the button was somehow pressed.

Your button definition should look something like this:

{drumObj.map(x => (
      <button
        className="drum-pad"
        ref={"drumButton" + x.trigger}
        key={x.id}
        id={x.id}
        onClick={() => drumHit(x.url, x.id)}
      > ...

We set a ref name for each button dynamically (try to find a way to define a unique ref name prefix in your component and define it only in one place), based on the char it represents. Once we have the references stored, we access them as needed in the handleKeyPress method like this:

handleKeyPress = event => {
   const drumKey = drumObj.find(obj => obj.keyCode === event.keyCode);

   if (drumKey) {
     this.refs["drumButton" + drumKey.trigger].focus();
     this.props.drumHit(drumKey.url, drumKey.id);
   }
};

I would actually replace the call to this.props.drumHit(...) for:

this.refs["drumButton" + drumKey.trigger].click();

The reason for that is because if you change the drumHit method name or signature in the future, you just need to update it in the onClick property of your button properties definition. As a good practice, always try to emulate this kind of events programmatically, instead of replicate the same behavior in different parts of your code.

So your handleKeyPress method should look something like this:

handleKeyPress = event => {
   const drumKey = drumObj.find(obj => obj.keyCode === event.keyCode);

   if (drumKey) {
     this.refs["drumButton" + drumKey.trigger].click();
     this.refs["drumButton" + drumKey.trigger].focus();
   }
};

I hope it helps!

Regards, Max.



来源:https://stackoverflow.com/questions/51413364/apply-button-active-styles-on-keypress-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!