简体   繁体   中英

Using a ref to get a size of a functional react component

I'm running React 16.8, I have a functional component that I need to measure the height of (so i can know how many children to display in the vertical space), looks like the best way to do so is with refs, but everything I've attempted so far results in the same warning: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? .

I've tried following examples online to use .forwardRef but I must not be setting it up correctly. Any help appreciated.

Here's the relevant code:

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

and here's 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.....
  }
`)

As per the warning, and as explained in the docs , Functional components don't support the ref attribute as they don't have instances like class components.

You are on the correct path with forwardRef , however, it needs to be used on the Function Component directly, in this case StyledDayGrid eg

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

function DayGrid(props) {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM