簡體   English   中英

Material-UI:以編程方式觸發懸停效果

[英]Material-UI: Trigger hover effect programmatically

我正在我的應用程序中呈現以下Material-UI組件:

const handleSetActive = _spyOn => {
  linkEl.current.focus();
};

const linkEl = useRef(null);

return (
    <ListItem
      button
      component={SmoothScrollLink}
      to={cutTo}
      spy
      smooth
      offset={(phone ? -theme.mixins.toolbar.minHeightPhone : -theme.mixins.toolbar.minHeightDesktop) - 20}
      duration={500}
      onSetActive={handleSetActive}
      // className={classNames(spyOn === cutTo && classes.hover)}
      ref={linkEl}
      {...other}
    />
)

它使用react-scroll包,只要滾動經過該特定ListItem就會觸發onSetActive

我想以最簡單的方式使ListItem來自 Material-UI )在handleSetActive觸發時啟用其懸停效果。

我怎樣才能最好地做到這一點?

以下是與ListItem懸停狀態相關的默認樣式部分:

export const styles = theme => ({
  /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
  root: {
    '&$selected, &$selected:hover': {
      backgroundColor: theme.palette.action.selected,
    },
  },
  /* Styles applied to the inner `component` element if `button={true}`. */
  button: {
    transition: theme.transitions.create('background-color', {
      duration: theme.transitions.duration.shortest,
    }),
    '&:hover': {
      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
    },
  },
  /* Styles applied to the root element if `selected={true}`. */
  selected: {},
});

由於在您的情況下您有button={true} ,您想要的樣式可以通過應用以下內容的 CSS 類來實現:

      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,

這是一個沙箱,顯示使用 react-scroll 的LinkactiveClass屬性來應用具有此樣式的類: https : activeClass

這是另一個使用 ref 直接在 DOM 節點上應用類的沙箱: https : //codesandbox.io/s/reactscroll-using-ref-9w8ki 但是您不應該使用這種方法(僅出於學習目的展示它),因為它比activeClass方法做更多的工作(表現會更差)並且非常脆弱,因為由於其他原因重新渲染可能會消除通過DOM。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM