preface
This article will introduce the React project in conjunction with MOBx to extract browser keyboard events. It only summarizes some implementation ideas in the process for reference.
thinking
How to perform the corresponding keyboard function in different pages if you pull out? Here comes the idea of using the mobx repository to go in and store changes to the corresponding function
encapsulation
Start by creating a Mobx repository along these lines
Create a new abstract class file
import { action, observable } from "mobx";
export default abstract class APageModel {
@observable F1 = (): boolean= > {
console.log("F1");
return false;
};
/** * listen for keyboard events */
@action handleOnKey(): void {
document.onkeydown = (e) = > {
const { keyCode } = e;
/** * whether to use keyboard events in the page ** */
let returnValue = false;
/ / execution
switch (keyCode) {
case 112:
returnValue = this.F1();
break;
}
if(returnValue) { e.preventDefault(); }}; }}Copy the code
First observablename is the function F1 and then creates an execution function to listen for keyboard events to execute the corresponding function
use
inheritance
Create a page repository that inherits our abstract class and changes the contents of the abstract class to be overridden by the corresponding keyboard function
import { action, observable } from "mobx";
import APageModel from "./abstract/APageModel";
export default class AppModel extends APageModel {
@observable keyName = "";
F1 = () = > {
this.setKeyName("F1");
return true;
};
@action
setKeyName(value: string) :void {
this.keyName = value; }}Copy the code
Page use
App.tsx
import React from "react";
import { observer } from "mobx-react";
import APage from "./abstract/APage";
import AppModel from "./AppModel";
interface AppProps {}
interface AppState extends AppModel {
keyName: string;
}
@observer
class App extends APage<AppProps.AppState> {
protected createModel(): AppState {
// Import to the repository
return new AppModel();
}
componentDidMount() {
/ / to monitor
this.model.handleOnKey();
}
public render() {
let { keyName } = this.model;
return <div>You just pressed: {keyName}</div>; }}export default App;
Copy the code
As shown in figure
At the end
- Project address: github.com/wangjinshen…
- Feel the harvest of friends welcome to praise, pay attention to a wave!