是否可以在div上使用MUI的触摸波纹效果?

Sim*_*zzi 14 reactjs material-ui ripple-effect

我读过类似问题的不同答案,但它们都是旧的,并且似乎不适用于最新版本的 MUI。

我需要在 div 上应用触摸波纹效果,但我无法使用按钮或元素,ButtonBase因为其中还有另一个按钮。

预先感谢您的回复。

Nea*_*arl 17

是的,您可以用来TouchRipple模拟涟漪效应。该组件没有文档记录,但您可以查看它的使用方式ButtonBase并自己学习使用它。

首先,您需要传递一个引用TouchRipple并在您想要分别启动或停止效果时调用 or ref.current.start(e)ref.current.stop(e)

e是事件对象。当你调用时start(e),它需要鼠标或触摸位置(来自mousedowntouchstart事件)来知道从哪里开始波纹效果()。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>
  );
}
Run Code Online (Sandbox Code Playgroud)

现场演示

编辑 66888248/how-do-i-programatically-show-ripple-effect-with-material-ui


小智 16

您可以使用ButtonBaseAPI

使用 ButtonBase API,您可以将componentprop 作为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;
Run Code Online (Sandbox Code Playgroud)