尝试在 React 中从父 element/Component 获取 ComputedStyle

Trying to getComputedStyle from parent element/Component in React

我需要计算父元素的背景颜色以传递给图像组件。这是必需的,因为我正在使用 Contentful API 动态渲染图像,并且我必须提供 bg 颜色查询参数。

目前这不起作用:

import Card, { CardContent } from 'components/Card';
import React, { Component, PropTypes } from 'react';

import Image from 'components/Image';
import Link from 'react-router/lib/Link';

export default class Expertise extends Component {
  
  componentDidMount()   {
    console.log(window.getComputedStyle(this._bg, null).getPropertyValue('backgroundColor'));
  }
  
  _renderColumned() {
    return (
      <Card
        layout={this.props.layout}
        additionalClasses={['expertise-item-container']}
        automationId={`expertise-container-${this.props.id}`}
        ref={node => (this._bg = node)}
      >
        <CardContent layout={'text'} theme={'transparent'} padded>
          <h3 className="expertise-headline h4" data-automation={`expertise-headline-${this.props.id}`}>
            <span className="h1 card-grid-enumeration">{this.props.displayNumber}</span>
            {this.props.headline}
          </h3>
          <p className="expertise-description" data-automation={`expertise-description-${this.props.id}`}>{this.props.description}</p>
          { this.props.url && this.props.linkText ?
            <Link className="expertise-link" data-automation={`expertise-link-${this.props.id}`} to={this.props.url}>{this.props.linkText}</Link> :
              null }
        </CardContent>
        <CardContent layout={'image'} theme={'transparent'} padded>
          <Image url={this.props.media.url} alt={this.props.media.alt} aspectRatio={'rectangle'} fit={'pad'} automationId={`expertise-image-${this.props.id}`} background={"F4F4F4"} />
        </CardContent>
      </Card>
    );
  }

  _renderStacked() {
    return (
      <div
        className="expertise-item-container centered"
        data-automation={`expertise-container-${this.props.id}`}
        // ref={image => (this._image = image)}
        ref={node => (this._bg = node)}
      >
        <h3 className="expertise-headline h4" data-automation={`expertise-headline-${this.props.id}`}>
          <span className="h1 card-grid-enumeration">{this.props.displayNumber}</span>&nbsp;
          {this.props.headline}
        </h3>
        <p className="expertise-description" data-automation={`expertise-description-${this.props.id}`}>{this.props.description}</p>
        <Image url={this.props.media.url} alt={this.props.media.alt} aspectRatio={'banner'} fit={'pad'} automationId={`expertise-image-${this.props.id}`} ref={node => (this._image = node)} background={"F4F4F4"} />
        { this.props.url && this.props.linkText ?
          <Link className="expertise-link" data-automation={`expertise-link-${this.props.id}`} to={this.props.url}>{this.props.linkText}</Link> :
            null }
      </div>
    );
  }

  render() {
    return this.props.layout === 'columned' ?
      this._renderColumned() :
      this._renderStacked();
  }

}

Expertise.propTypes = {
  id: PropTypes.string.isRequired,
  layout: PropTypes.oneOf(['columned', 'stacked']).isRequired,
  headline: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  media: PropTypes.object.isRequired,
  url: PropTypes.string,
  linkText: PropTypes.string,
  displayNumber: PropTypes.number.isRequired
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

具体来说,getComputedStyle 报告 Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

只是试图获得 background-color 成功,最终我会将其与 background prop 中给 Image 组件的默认值进行比较。

我认为问题是在渲染组件之前无法获得计算样式(与无法获得 ref 的原因相同)。您可以在其本地 state 中存储 parent bgcolor 样式(开头为 nullundefinedwhite,无论如何)并将其传递给组件的 children。组件渲染完成后(componentDidMount()window.addEventListener("load", ...))你可以调用parentsetState()方法来设置它的bgcolor状态()。然后这个组件将被重新渲染,它的 children 将访问它的 bgcolor.