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

seb*_*ian 9 animation typescript reactjs gsap material-ui

如何使用 TypeScript将ref添加到React 中的material-ui Box组件中?这对于允许GreenSock / GSAP等动画库对节点进行动画处理非常重要。根据material-ui文档,使用itemRef将不起作用,因为它需要使用findDOMNode,而findDOMNode在严格模式下已被弃用(为并发React做准备),并且由于虚拟DOM渲染,进一步可能会中断。

seb*_*ian 3

如果无法将引用关联所有MATERIAL-UI 生成的节点,就没有可靠的方法来集成针对特定节点的动画库。

Material-ui GitHub 项目上有几个相关问题。我在问题 #17010上发布了一个解决方法,直到 Material-ui 包含向所有生成的节点添加引用的功能。

相关问题:

  • 如何将 ref 添加到 Box 组件?第19284章
  • [Box] 允许引用 Box #19275
  • TypeScript 定义中的 Box 缺少引用#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>
Run Code Online (Sandbox Code Playgroud)

注意:使用 @material-ui/core/styles 不起作用,需要使用情感styled-components由于样式组件独特生成的动画闪烁问题,我们被迫在样式组件上使用情感。