ReactJS get rendered component height

前端 未结 9 1656
夕颜
夕颜 2020-12-29 02:29

I\'m attempting to integrate or create a React version of https://github.com/kumailht/gridforms, to do so I need to normalize the height of the columns inside of the row. Th

9条回答
  •  盖世英雄少女心
    2020-12-29 03:22

    According to current React docs, the preferred use of refs is to pass it a callback rather than a string to be accessed elsewhere in this.refs. So to get the height of a div (within a React.Component class):

    componentDidMount() {
      this.setState({ elementHeight: this.divRef.clientHeight });
    }
    
    render() {
      return 
    this.divRef = element}>
    }

    Or it works this way, though I don't know if this is advisable since we set state in the render method.

    getHeight(element) {
      if (element && !this.state.elementHeight) { // need to check that we haven't already set the height or we'll create an infinite render loop
        this.setState({ elementHeight: element.clientHeight });
      }
    }
    
    render() {
      return 
    ; }

    Reference: https://facebook.github.io/react/docs/more-about-refs.html

提交回复
热议问题