[英]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 的Link
的activeClass
属性来应用具有此样式的类: https : activeClass
。
这是另一个使用 ref 直接在 DOM 节点上应用类的沙箱: https : //codesandbox.io/s/reactscroll-using-ref-9w8ki ; 但是您不应该使用这种方法(仅出于学习目的展示它),因为它比activeClass
方法做更多的工作(表现会更差)并且非常脆弱,因为由于其他原因重新渲染可能会消除通过DOM。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.