[英]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.