无法从 React Ref 获取偏移高度



我正在尝试React render方法中获取div元素的大小。但它总是offsetHeight,offsetWidth 0.

我可以在console.log时看到offsetHeight,offsetWidth的实际值。

如何在组件渲染后获取容器div ref 元素的实际大小?

这是我的实现。

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            height:0,
            width:0,
        }
        this.containerRef = React.createRef()
    }
    componentDidMount(){
        console.log(this.containerRef)
        //saw offsetWidth and offsetHeightSize (300,700)
          const {offsetHeight,offsetWidth} = this.containerRef.current
          this.setState({
              width:offsetWidth,//getting 0
              height:offsetHeight //getting 0
          })
    }
    render() {
         const {width,height} = this.state
        return (
            <div ref={this.containerRef}>
              {`width:${width}-height:${height}`}
            </div>
        );
    }
}

请帮忙。

谢谢。

React Hook 解决方案

const useResize = (myRef) => {
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)
  const handleResize = () => {
    setWidth(myRef.current.offsetWidth)
    setHeight(myRef.current.offsetHeight)
  }
  useEffect(() => {
    myRef.current && myRef.current.addEventListener('resize', handleResize)
    return () => {
      myRef.current.removeEventListener('resize', handleResize)
    }
  }, [myRef])
  return { width, height }
}

const MyComponent = () => {
  const componentRef = useRef()
  const { width, height } = useResize(componentRef)
  return (
    <div ref={componentRef}>
      <p>width: {width}px</p>
      <p>height: {height}px</p>
    <div/>
  )
}

基于类的解决方案

class MyComponent extends Component {
  constructor(props){
    super(props)
    this.myDiv = React.createRef()
  }
  componentDidMount () {
    console.log(this.myDiv.current.offsetHeight)
  }
  render () {
    return (
      <div ref={this.myDiv}>element</div>
    )
  }
}

最新更新