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

标签 javascript reactjs material-ui

我正在我的应用程序中呈现以下 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 ( from Material-UI ) 在 handleSetActive 触发时启用其悬停效果。

我怎样才能最好地做到这一点?

最佳答案

以下是 default styles 的部分内容与 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://codesandbox.io/s/reactscroll-gppym .

这是另一个使用 ref 直接在 DOM 节点上应用类的沙箱:https://codesandbox.io/s/reactscroll-using-ref-9w8ki ;但是你不应该使用这种方法(仅出于学习目的展示它),因为它比 activeClass 方法做更多的工作(性能会更差)并且非常脆弱,因为由于其他原因可能会重新渲染清除通过 DOM 应用的类。

关于javascript - Material-UI:以编程方式触发悬停效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318783/

相关文章:

reactjs - 为什么material-ui占用太多空间?

javascript - 在 React Native 中连接日期和时间返回 'Invalid Date'

javascript - 从标签中挑出 href =""并通过 javascript 更改它

javascript - 为什么这是跨域请求

javascript - 组件之间传递值

reactjs - Material-UI 选择 e.target.value 未定义

javascript - 如何在没有类的情况下生成对象的新实例?

javascript - Formik 元素类型无效

forms - 在兄弟组件 Reactjs 中调用函数

javascript - 如何修复 '' findDOMNode is deprecated in StrictMode'' 错误?