gpt4 book ai didi

javascript - 在 React 中动态添加后 getElementById

转载 作者:行者123 更新时间:2023-12-02 03:01:49 25 4
gpt4 key购买 nike

我正在我的 React 功能组件中动态添加卡片。卡存储在 State 中。我对它们进行了映射并为每个它们提供了 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>;
}

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

最佳答案

您也可以在功能组件中使用ref。有一个名为 useRef 的钩子(Hook)。

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

关于javascript - 在 React 中动态添加后 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59798802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com