首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ReactJS获取渲染组件高度

ReactJS获取渲染组件高度
EN

Stack Overflow用户
提问于 2015-07-28 03:37:48
回答 9查看 110.9K关注 0票数 36

我正在尝试集成或创建https://github.com/kumailht/gridforms的React版本,为此,我需要规范化行中列的高度。原件采用网格行的高度,并将其应用于子列。

我曾计划获取行的高度,然后将其映射到孩子的属性,尽管从我的尝试来看,我认为这可能不是理想的方式,甚至不可能?

下面是我当前的代码。

代码语言:javascript
运行
复制
GridRow = React.createClass({
  render(){
        const children = _.map(this.props.children, child => {
            child.props.height = // somehow get row component height
            return child
        })
    return (<div data-row-span={this.props.span} {...this.props}>
      {children}
    </div>)
  }
})

GridCol = React.createClass({
  render(){
    return (<div data-field-span={this.props.span} style={{height:this.props.height}} {...this.props}>
      {this.props.children}
    </div>)
  }
})

我测试了这样设置样式,它可以工作,但是获取高度不是这样。

编辑:小提琴:

https://jsfiddle.net/4wm5bffn/2/

EN

回答 9

Stack Overflow用户

发布于 2016-05-21 15:53:04

回答有点晚了,但从技术上讲,你可以通过这种方式获得元素高度:

代码语言:javascript
运行
复制
var node = ReactDOM.findDOMNode(this.refs[ref-name]);
if (node){
  var calculatedHeight = node.clientHeight;
}
票数 19
EN

Stack Overflow用户

发布于 2016-06-03 02:57:45

根据当前的React文档,refs的首选用法是传递给它一个回调,而不是要在this.refs中的其他地方访问的字符串。因此,要获取div的高度(在React.Component类中):

代码语言:javascript
运行
复制
componentDidMount() {
  this.setState({ elementHeight: this.divRef.clientHeight });
}

render() {
  return <div ref={element => this.divRef = element}></div>
}

或者它是这样工作的,尽管我不知道这是否可取,因为我们在render方法中设置了state。

代码语言:javascript
运行
复制
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 <div ref={this.getHeight}></div>;
}

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

票数 19
EN

Stack Overflow用户

发布于 2017-04-13 11:40:26

不知道其他人,但我总是必须在下一个刻度时得到它,以确保获得正确的高度和宽度。感觉有点老生常谈,但我猜测这与渲染周期有关,但我现在就接受它。在某些用例中,onLayout可能工作得更好。

代码语言:javascript
运行
复制
componentDidMount() {
  setTimeout(() => {
    let ref = this.refs.Container
    console.log(ref.clientHeight)
    console.log(ref.clientWidth)
  }, 1)
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31661790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档