在 React 中动态添加后的 getElementById

getElementById after dynamically adding it in React

我正在我的 React 功能组件中动态添加卡片。卡片存储在状态中。我映射它们并为它们每个人提供 id。在这些卡片上单击我成功获得了他们的 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>;
}

我尝试学习参考,但它们仅适用于 class 组件。那么我如何在 React 中通过 id 访问我的元素?

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

Note: Never interact directly with DOM until or unless there is no api available in react to solve the problem for that particular use case.

In react it's not recommended to interact directly with dom. Always use react apis to interact with dom. React is designed to hide the DOM because they want to abstract the DOM away. By using the DOM directly you break the abstraction and make your code brittle to changes introduced in the library.

React is maintaining a virtual DOM if we make any changes in actual DOM directly then react will not be aware of this change and this can lead to some unexpected behavior .

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>;
}

来自官方文档的示例。

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>
    </>
  );
}