在 React 中动态添加后的 getElementById

vyt*_*ute 2 javascript reactjs use-effect use-state use-ref

我正在我的 React 功能组件中动态添加卡片。卡片存储在状态中。我映射它们并给每个人提供 id。OnClick 在那些卡片上我成功地获得了他们的 id。现在我想 getElementById 来改变卡片颜色:

function Clicked(pressedGifId) {
  if (pressedGifId === 'correctGif') CorrectMatch();
  else WrongMatch();
}

function CorrectMatch(pressedGifId) {
  // / THERE I GET Element: null
  console.log('Element:', document.getElementById(pressedGifId));
}
function WrongMatch() {
  console.log('wrong a match!');
}

export default function GameObject(props) {
  const addedToGameGif = [];
  const [pressedGifId, gifPressed] = useState(null);
  const [photoCards, setPhotoCards] = useState([]);

  useEffect(() => {
    Clicked(pressedGifId);
  }, [pressedGifId]);

  // add randomly picked photos to addedToGameGif array
  // ...

  addedToGameGif.map(gifId =>
    photoCards.push(
      <Card id={gifId} onClick={() => gifPressed(gifId)}>
        text
      </Card>,
    ),
  );

  return <div>{photoCards}</div>;
}
Run Code Online (Sandbox Code Playgroud)

我尝试学习 refs,但它们仅适用于类组件。那么如何在 React 中通过 id 到达我的元素呢?

Soh*_*raf 5

您也可以ref在功能组件中使用。有一个钩子叫useRef.

注意:永远不要直接交互,DOM直到或除非反应中没有可用的 api 来解决该特定用例的问题。

在反应中,不建议直接与 dom 交互。始终使用 react apis 与 dom 交互。React 旨在隐藏 DOM,因为他们想将 DOM 抽象出来。通过直接使用 DOM,您可以打破抽象并使您的代码容易受到库中引入的更改的影响。

React 正在维护一个虚拟的,DOM如果我们DOM 直接在实际中进行任何更改,则react不会意识到此更改,这可能会导致一些意外行为。

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

export default function GameObject(props) {
  const addedToGameGif = [];
  const [pressedGifId, gifPressed] = useState(null);
  const [photoCards, setPhotoCards] = useState([]);
  const elemRef = useRef(null);

  useEffect(() => {
    Clicked(pressedGifId);
  }, [pressedGifId]);

  // add randomly picked photos to addedToGameGif array
  // ...

  addedToGameGif.map(gifId =>
    photoCards.push(
      <Card ref={elemRef} id={gifId} onClick={() => gifPressed(gifId)}>
        text
      </Card>
    )
  );

  return <div>{photoCards}</div>;
}

Run Code Online (Sandbox Code Playgroud)

来自官方文档的示例。

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)