我正在运行 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.....
}
`)
根据警告,正如文档中所解释的,功能组件不支持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>
)
}