简体   繁体   English

使用 ref 获取功能性反应组件的大小

[英]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()?我正在运行 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()? 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.我已经尝试在线使用以下示例来使用 .forwardRef,但我一定没有正确设置它。 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:这是 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.根据警告以及文档中的解释,功能组件不支持ref属性,因为它们没有类组件之类的实例。

You are on the correct path with forwardRef , however, it needs to be used on the Function Component directly, in this case StyledDayGrid eg您在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>
  )
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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