猿问

材料设计组件切换效果不起作用

我正在尝试将材质组件 IconButton 与 React 一起使用。

材料设计:https ://material-components.github.io/material-components-web-catalog/#/component/icon-button


它工作并显示元素并进行重复。但是切换不起作用。

这是我在 chrome 的 devtool 中的代码和元素树。

请教我解决方案。

import React, { useEffect } from 'react';

import { MDCIconButtonToggle } from '@material/icon-button';


const ButtonLike = () => {

  useEffect(() => {

    const iconToggle = new MDCIconButtonToggle(

      document.querySelector('.mdc-icon-button'),

    );

    iconToggle.on = true;

  });

  return (

    <button

      id="add-to-favorites"

      className="mdc-icon-button mdc-icon-button--on"

      aria-label="Add to favorites"

      aria-pressed="false"

    >

      <i className="material-icons mdc-icon-button__icon mdc-icon-button__icon--on">favorite</i>

      <i className="material-icons mdc-icon-button__icon">favorite_border</i>

    </button>

  );

};


export default ButtonLike;

元素树


<button id="add-to-favorites" class="mdc-icon-button mdc-icon-button--on" aria-label="Add to favorites" aria-pressed="false">

  <i class="material-icons mdc-icon-button__icon mdc-icon-button__icon--on">

    favorite

  </i>

  <i class="material-icons mdc-icon-button__icon">

    favorite_border

  </i>

</button>


ITMISS
浏览 133回答 1
1回答

慕标5832272

iconToggle您在内部实例化useEffect(),但您忽略了useEffect()采用第二个参数deps list的事实。没有它,该逻辑会在每次重新渲染时重新运行,这意味着您每次都iconToggle.on被设置回true,因此它保持在“开启”状态。作为旁注,选择 HTML 元素的更 React-ish 方式是 by useRef(),而不是document.querySelector()可能会找到其他不需要的元素import React, { useEffect, useRef } from 'react';import { MDCIconButtonToggle } from '@material/icon-button';const ButtonLike = () => {&nbsp; const buttonRef = useRef(null);&nbsp; useEffect(() => {&nbsp; &nbsp; const iconToggle = new MDCIconButtonToggle(buttonRef.current);&nbsp; &nbsp; iconToggle.on = true;&nbsp; }, []);&nbsp; // <-- You need to pass in an empty array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//&nbsp; &nbsp; &nbsp;to signal that you want this logic to run only once.&nbsp; return (&nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; ref={buttonRef}&nbsp; &nbsp; &nbsp; id="add-to-favorites"&nbsp; &nbsp; &nbsp; className="mdc-icon-button mdc-icon-button--on"&nbsp; &nbsp; &nbsp; aria-label="Add to favorites"&nbsp; &nbsp; &nbsp; aria-pressed="false"&nbsp; &nbsp; >&nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答