[英]React useRef hook: Cannot access a single item in ref array by index
[英]Cannot access <Button> with useRef()
我試圖在反應中使用 useRef 訪問我的按鈕元素。 但我不知道為什么當我點擊一個按鈕時它總是返回最后一個元素。
這是我的代碼
const selectPage = (value) => {
dispatch(Action.changePage(value));
console.log(ref.current);
};
const returnButton = (value) => {
return (
<button
onClick={() => {
selectPage(value);
}}
ref={ref}
>
<GiBeerStein />
</button>
);
};
return (
{returnButton(1)}
{returnButton(2)}
{returnButton(3)}
)
知道為什么嗎? 謝謝你。
您不應該手動更改 dom 來添加類名。 React 不知道您這樣做了,因此它在決定需要執行哪些未來更新時無法考慮您的更改。 在某些情況下,這可能會導致意外行為,反應改變你不想改變的東西,反之亦然。
相反,您應該使用 state。如果您只想一次激活一個按鈕,則 state 可以是一個數字,它是處於活動狀態的按鈕的索引:
const [activeIndex, setActiveIndex] = useState(-1);
const selectPage = (value) => {
dispatch(Action.changePage(value));
setActiveIndex(value - 1);
};
const buttons = [];
for (let i = 0; i < 3; i++) {
buttons.push(
<button
onClick={() => {
selectPage(i + 1);
}}
className={activeIndex === i ? "active" : undefined}
>
<GiBeerStein />
</button>
);
}
return <>{buttons}</>;
相反,如果您需要支持多個按鈕處於活動狀態,則可以將索引設為布爾數組:
const [active, setActive] = useState([false, false, false]);
const selectPage = (value) => {
setActiveIndex(prev => {
const next = [...prev];
next[value - 1] = !next[value - 1];
return next;
});
};
// ...
className={active[i] ? "active" : undefined}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.