React子节点高度不正确

时间:2015-09-03 04:52:57

标签: reactjs

我有两个组件ArticlesArticle。文章将在完成后发送ajax调用并重新呈现文章列表。

尝试在componentDidMount中获取每篇文章的高度时,有时会返回Article节点的不正确高度。但它在其他方法中返回正确的值。有没有办法在文章componentDidMount中找到正确的高度?

// Articles component
 var Articles = React.createClass({
  getInitialState: function() {
    return {
      articles: []
    };
  },

  componentDidMount: function() {
    $.ajax(api_url)
      .done(function(data) {
        if(this.isMounted()) {
          this.setState({
            articles: data.posts,
        });
    }.bind(this));
  },

  render: function() {
    var articles = this.state.articles.map(function(article, index) {
      return <Article key={article.id} article={article} index={index} />
    });

    return (
      <div className="articles">
        {articles}
      </div>
    )
  }
});

// Article component
var Article = React.createClass({

  propTypes: {
    article: React.PropTypes.object
  },

  getInitialState: function() {
    return {
      height: 0
    };
  },

  componentDidMount: function() {
    var node;

    node = React.findDOMNode(this);
    console.log(node.offsetHeight); // incorrect value
  },

  handleClick: function() {
    var node;

    node = React.findDOMNode(this);
    console.log(node.offsetHeight); // correct value
  },

  render: function() {
    return (
      <div className="article">
        <header className="intro-header">
          {this.setBanner()}
            <div className="container">
                <div className="row">
                    <div className="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                        <div className="post-heading">
                            <h1>{this.props.article.title}</h1>

                            <span className="meta">Posted by {this.props.article.author.name} on {this.props.article.date}</span>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <article>
            <div className="container">
                <div className="row">
                    <div className="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 content" dangerouslySetInnerHTML={{__html: this.props.article.content}}>
                    </div>
                </div>
            </div>
        </article>
      </div>
    )
  }
})

2 个答案:

答案 0 :(得分:4)

文章中是否有没有明确高度属性的图像?我以前经历过这个问题,那就是原因。

如果是这样,很可能是由于图像没有加载到componentDidMount上(很可能发生)并且可以通过向图像添加明确的宽度和高度来解决,或者如果不可能,则推迟初始化测量直到图像加载https://github.com/alexanderdickson/waitForImages

之类的东西

答案 1 :(得分:0)

如果您尝试让父母offsetHeight加入componentDidMount,那么您将获得undefined

The componentDidMount() method of child components is invoked before that of parent components.

请参阅https://facebook.github.io/react/docs/component-specs.html