Typescript/React:如何将 ref 添加到 material-ui Box 组件?

Typescript/React: How can a ref be added to a material-ui Box component?

如何将ref添加到material-ui Box component in React, using TypeScript? This is important to allow animation libraries like GreenSock / GSAP to animate nodes. Per material-ui docs,使用itemRef是不行的因为它需要使用 findDOMNode ,它在严格模式下被弃用(为并发 React 做准备)并且进一步可能由于虚拟 DOM 渲染而中断.

无法将 ref 关联到 ALL MATERIAL-UI GENERATED NODES,有不是针对特定节点集成动画库的可靠方法。

material-ui GitHub 项目中有几个相关问题。我在 Issue #17010 上发布了一个解决方法,直到 material-ui 包含添加 ref[=39= 的能力] 到所有生成的节点。

相关问题:

  • 如何将 ref 添加到 Box 组件? #19284
  • [Box] 允许引用 Box #19275
  • TypeScript 定义中的 Box 缺少 ref #17010

临时解决方法:

// 1. Import style library, either Emotion or Styled-Components
import styled from "@emotion/styled";

// 2. Recreate the Material-UI Box with a styled component
const StyledBox = styled(Box)``;

// 3. Usage in the render
<StyledBox ref={boxRef}>Box Content</StyledBox>

注意:使用@material-ui/core/styles不起作用,要求ui使用emotion or styled-components由于 styled-components 独有的动画闪烁问题,我们不得不在 styled-components 上使用情感。