我已经阅读了类似问题的不同答案,但它们都很旧,似乎在最新版本的 MUI 中不起作用。
我需要在 div 上应用触摸波纹效果,但我不能使用按钮或ButtonBase
元素,因为其中还有另一个按钮。
提前感谢您的回复。
我已经阅读了类似问题的不同答案,但它们都很旧,似乎在最新版本的 MUI 中不起作用。
我需要在 div 上应用触摸波纹效果,但我不能使用按钮或ButtonBase
元素,因为其中还有另一个按钮。
提前感谢您的回复。
是的,您可以使用它TouchRipple
来模拟涟漪效应。该组件未记录在案,但您可以查看它的使用ButtonBase
方式并自己学习使用它。
首先,您需要将 ref 传递给TouchRipple
并调用ref.current.start(e)
orref.current.stop(e)
当您想要分别启动或停止效果时。
e
是事件对象。当您调用时start(e)
,它需要鼠标或触摸位置(从mousedown
或touchstart
事件)知道从哪里开始涟漪效果(Source)。center
您可以通过将props设置为来覆盖此行为true
,这使得波纹效果始终从中间开始。
以下是帮助您入门的最低限度的工作示例:
function App() {
const rippleRef = React.useRef(null);
const onRippleStart = (e) => {
rippleRef.current.start(e);
};
const onRippleStop = (e) => {
rippleRef.current.stop(e);
};
return (
<div
onMouseDown={onRippleStart}
onMouseUp={onRippleStop}
style={{
display: "inline-block",
padding: 8,
position: "relative",
border: "black solid 1px"
}}
>
Button
<TouchRipple ref={rippleRef} center={false} />
</div>
);
}
ButtonBase
API使用 ButtonBase API,您可以将component
prop 作为div
或任何您想要的组件传递
import { ButtonBase, Typography } from "@mui/material";
const App = () => {
return (
<ButtonBase component="div">
<Typography fontSize="1.2rem">Hello, I'm a div with MUI Ripple Effect!</Typography>
</ButtonBase>
)
}
export default App;