反应处理事件侦听器问题

时间:2020-06-29 18:45:34

标签: javascript reactjs events addeventlistener

我正在尝试为freeCodeCamp项目构建一个简单的鼓机,但是遇到一个问题: 当我尝试从Drum组件更新App组件状态时,出现错误。

Drum.js:17 Uncaught TypeError: Cannot read property 'play' of null
    at playAudio (Drum.js:17)
    at HTMLDocument.handleKeyPress (Drum.js:12)

第一次按键有效,但是从第二次按键出现此错误。如果单击元素,则一切正常。 我想我没有正确使用useEffect,但我无法确切了解自己在做什么。

App.js

const App = () => {
  const [note, setNote] = useState("");

  const handleNote = (e) => {
    console.log(e.id);
    setNote(e.id);
  };

  return (
    <div className="App">
      <div id="drum-machine">
        <div id="display">
          {sounds.map((sound, i) => (
            <Drum
              key={i}
              keyTrigger={sound.key}
              audio={sound.sound}
              handleNote={handleNote}
            />
          ))}
        </div>
        <SmallDisplay />
      </div>
    </div>
  );
};

Drum.js

const Drum = ({ keyTrigger, audio, handleNote }) => {
  const audioRef = React.createRef();

  useEffect(() => {
    document.addEventListener("keypress", handleKeyPress);
  }, []);

  const handleKeyPress = (e) => {
    if (e.code === `Key${keyTrigger}`) {
      playAudio();
    }
  };

  const playAudio = () => {
    audioRef.current.play();
  };

  const handlePlay = (e) => {
    handleNote(e.target);
  };

  return (
    <div className="drum-pad" id={audio} onClick={playAudio}>
      {keyTrigger}
      <audio
        id={keyTrigger}
        className="clip"
        ref={audioRef}
        src={audio}
        onPlay={handlePlay}
      />
    </div>
  );
};

您可以在此处找到完整的代码 https://codepen.io/mugg84/pen/YzwraXw?editors=0011

感谢您的帮助!

0 个答案:

没有答案