首页 > 解决方案 > 使用 ref 获取功能性反应组件的大小

问题描述

我正在运行 React 16.8,我有一个需要测量高度的功能组件(所以我可以知道在垂直空间中显示多少个孩子),看起来最好的方法是使用 refs,但一切到目前为止,我尝试过的结果相同的警告:Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

我已经尝试在线使用以下示例来使用 .forwardRef 但我一定没有正确设置它。任何帮助表示赞赏。

以下是相关代码:

import React, { useState, useEffect, useRef } from 'react'

const ForwardingStyledDayGrid = React.forwardRef((props, ref) => (
  <StyledDayGrid ref={ref}>{props.children}</StyledDayGrid>
))

function DayGrid(props) {

  const [height, setHeight] = useState(0)

  const dayGridRef = useRef(null)

  useEffect(() => {
    setHeight(dayGridRef.current.clientHeight)
  })

  return (
    <ForwardingStyledDayGrid
      ref={dayGridRef}
      inCurrentMonth={props.inCurrentMonth}

    >
      {children}
    </ForwardingStyledDayGrid>
  )
}

export default DayGrid

这是 StyledDayGrid:

import React from 'react'
import styled from 'styled-components'
import withTheme from '@material-ui/core/styles/withTheme'

import Grid from '@material-ui/core/Grid'

const StyledDayGrid = withTheme(styled(({ inCurrentMonth, ...rest }) => (
  <Grid {...rest} />
))`
  && {
    overflow: hidden;
    padding: 2px;
    background-color: ${props =>
      !props.inCurrentMonth && props.theme.monthView.nonCurrentMonth};
    etc.....
  }
`)

标签: javascriptreactjsreact-hooks

解决方案


根据警告和文档中的解释,功能组件不支持该ref属性,因为它们没有类组件之类的实例。

您在正确的路径上forwardRef,但是,它需要直接在功能组件上使用,在这种情况下,StyledDayGrid例如

const StyledDayGrid = React.forwardRef((props, ref) => {
  // use 'ref' internally
  return (...);
});

function DayGrid(props) {

  const dayGridRef = useRef(null)
  ...
  return (
    <StyledDayGrid ref={dayGridRef}>
      {children}
    </StyledDayGrid>
  )
} 

推荐阅读