简体   繁体   中英

useRef() error: cannot set property disabled of null when trying to focus on a textarea

I am trying to get the textarea to be focused on so the user doesn't have to click start then click on the textarea, but keep getting an error when i click start, using codesandbox IDE.

Bit stuck now so not sure what i can do to fix it, the code runs fine when inputRef.current.focus and inputRef.current.disabled aren't included in the startGame() function.

import React, { useState, useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  const STARTING_TIME = 5;

  const [text, updateText] = useState("");
  const [time, setTime] = useState(STARTING_TIME);
  const [isTimeRunning, setIsTimeRunning] = useState(false);
  const [wordCount, setWordCount] = useState(0);
  const inputRef = useRef(null)

  function handleChange(event) {
    const { value } = event.target;
    updateText(value);
  }

  function startGame() {
    setIsTimeRunning(true);
    setTime(STARTING_TIME);
    updateText("");
    setWordCount(0);
    inputRef.current.disabled = false;
    inputRef.current.focus();
  }

  function endGame() {
    setIsTimeRunning(false);
    const numWords = countWords(text);
    setWordCount(numWords);
  }

  function countWords(text) {
    const wordsArr = text.trim().split(" ");
    const filteredWords = wordsArr.filter(word => word !== "");
    return filteredWords.length;
  }

  useEffect(() => {
    if (isTimeRunning && time > 0) {
      setTimeout(() => {
        setTime(time => time - 1);
      }, 1000);
    } else if (time === 0) {
      endGame();
    }
  }, [time, isTimeRunning]);

  return (
    <div>
      <h1>Speed Typing Game</h1>
      <textarea
        onChange={handleChange}
        value={text}
        disabled={!isTimeRunning}
      />
      <h4>Time remaning: {time} </h4>
      <button type="button" onClick={startGame} disabled={isTimeRunning}>
        Start Game
      </button>
      <h1>Word Count: {wordCount} </h1>
    </div>
  );
}

Errors shown in the IDE console log below:

控制台错误日志

You have to attach the inputRef to your textArea.

<textarea
  onChange={handleChange}
  value={text}
  disabled={!isTimeRunning}
  ref={inputRef}
/>

Find out more about React Refs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM