In react, I want to add a keyboard monitoring method when the value of a is true, and delete the keyboard monitoring method when the value of a is false. How to achieve this?

In React, you can use useEffecthooks to listen for keyboard events and add or remove event listeners based on conditions. Specifically, you can determine whether to add or remove a keyboard event listener useEffectbased on the value of internally . aHere is an example that demonstrates how to adynamically add or remove a keyboard event listener based on the value of :

import React, {
    
     useState, useEffect } from 'react';

function MyComponent() {
    
    
  const [a, setA] = useState(false);

  useEffect(() => {
    
    
    const handleKeyPress = (event) => {
    
    
      if (a) {
    
    
        console.log('Key pressed:', event.key);
      }
    };

    window.addEventListener('keydown', handleKeyPress);

    return () => {
    
    
      window.removeEventListener('keydown', handleKeyPress);
    };
  }, [a]); // 依赖项数组包含 a,当 a 发生变化时重新运行 useEffect

  const toggleA = () => {
    
    
    setA(!a);
  };

  return (
    <div>
      <p>a is {
    
    a ? 'true' : 'false'}</p>
      <button onClick={
    
    toggleA}>Toggle a</button>
    </div>
  );
}

export default MyComponent;

In the above example, useEffectthe internal handleKeyPressfunction adetermines whether to handle keyboard events based on the value of . When athe value trueis , the keyboard event will be monitored and triggered; when athe value falseis , the keyboard event listener will be removed and will no longer be triggered.

When you click the "Toggle a" button, athe value of will switch between trueand , thereby realizing the need to add or remove keyboard event listeners based on the value of .falsea

Guess you like

Origin blog.csdn.net/z2000ky/article/details/132409543