4

我已经阅读了类似问题的不同答案,但它们都很旧,似乎在最新版本的 MUI 中不起作用。

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

提前感谢您的回复。

4

2 回答 2

5

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

首先,您需要将 ref 传递给TouchRipple并调用ref.current.start(e)orref.current.stop(e)当您想要分别启动或停止效果时。

e是事件对象。当您调用时start(e),它需要鼠标或触摸位置(从mousedowntouchstart事件)知道从哪里开始涟漪效果(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>
  );
}

现场演示

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

于 2021-04-22T12:02:51.643 回答
0

您可以使用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;
于 2022-02-24T09:25:05.757 回答