1 回答

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
iconToggle您在內(nèi)部實(shí)例化useEffect(),但您忽略了useEffect()采用第二個(gè)參數(shù)deps list的事實(shí)。沒(méi)有它,該邏輯會(huì)在每次重新渲染時(shí)重新運(yùn)行,這意味著您每次都iconToggle.on被設(shè)置回true,因此它保持在“開(kāi)啟”狀態(tài)。
作為旁注,選擇 HTML 元素的更 React-ish 方式是 by useRef(),而不是document.querySelector()可能會(huì)找到其他不需要的元素
import React, { useEffect, useRef } from 'react';
import { MDCIconButtonToggle } from '@material/icon-button';
const ButtonLike = () => {
const buttonRef = useRef(null);
useEffect(() => {
const iconToggle = new MDCIconButtonToggle(buttonRef.current);
iconToggle.on = true;
}, []); // <-- You need to pass in an empty array
// to signal that you want this logic to run only once.
return (
<button
ref={buttonRef}
id="add-to-favorites"
className="mdc-icon-button mdc-icon-button--on"
aria-label="Add to favorites"
aria-pressed="false"
>
);
}
添加回答
舉報(bào)