Material-UI:以编程方式触发悬停效果

7
我正在应用程序中渲染以下的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触发时启用其悬停效果。
我应该如何最好地实现这一点?
1个回答

3
以下是与 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的标签中的activeClass属性,可以应用以下样式:https://codesandbox.io/s/reactscroll-gppym
另一个沙盒则是使用ref直接在DOM节点上应用类名:https://codesandbox.io/s/reactscroll-using-ref-9w8ki;但不建议采用这种方法(仅供学习参考),因为它会做更多的工作(性能较差),而且由于重新渲染其他原因可能会清除通过DOM应用的类。

当我已经有一个在正确位置触发的处理程序时,不得不在这里创建状态感觉有点不自然。是否可能通过某种方式使用 ref 避免状态? - Magnus
是的,您可以通过在 ListItem 上使用 ref 直接在 DOM 中切换类来避免状态。只要您的应用程序不需要出于其他原因知道哪个项目处于活动状态,这将很好地工作。 - Ryan Cogswell
谢谢Ryan。你能给我一个如何做到这一点的例子吗?我很困扰。 - Magnus
当然。请创建一个 CodeSandbox,其中包含您设置的关键方面的工作示例(例如使用 react-scroll 的列表项,并使用 onSetActive/Inactive),我将对其进行增强以显示切换类。 - Ryan Cogswell
感谢您的耐心等待,Ryan。这里是代码沙盒,暂时使用状态方法(还没有完全完成,在滚动时速度不够快):https://codesandbox.io/s/gatsbystarterdefault-290qv - Magnus
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接