访问来自其他组件的反应组件的状态

时间:2016-12-13 09:34:57

标签: reactjs

我有以下微调器

import React, { Component } from 'react'
import './Spinner.scss'

export default class Spinner extends Component {
  constructor(props) {
    super(props);
    this.state = {showLoading: true};
  }

  render () {
    return (
      <div className="spinner">
        <div className="double-bounce1"></div>
        <div className="double-bounce2"></div>
      </div>
    )
  }
}

从其他组件我想显示或隐藏此微调器这里是组件的代码:

import React, { Component } from 'react'

import RTable from '../../../components/RTable/RTable'

import Spinner from '../../../components/Spinner/Spinner'

import CsvDownload from '../containers/CsvDownloadContainer'
export default class Table extends Component {

  _renderBreadcrumb () {
    const { breadcrumb, handleBreadcrumbClick } = this.props
    return (
      <ol className="breadcrumb">
        {(breadcrumb || []).map(el => {
          return (
            <li key={el.datasetKey}>
              <a onClick={() => { handleBreadcrumbClick(el.granularity, el.datasetKey, el.datasetKeyHuman) }}>
                {el.datasetKeyHuman}
              </a>
            </li>
          )
        })}
      </ol>
    )
  }

  render () {
    const { datasetRows, columns, metadata, showLoading } = this.props

    return (
      <div className="row">
        <div className="col-sm-12">
          {this._renderBreadcrumb()}
          <RTable rows={datasetRows} columns={columns} metadata={metadata} />
          { this.props.showLoading ? <Spinner /> : null }
          <CsvDownload />
        </div>
      </div>
    )
  }

}

你可以看到我尝试使用以下方式显示或隐藏微调器:

{ this.props.showLoading ? <Spinner /> : null }

但我总是变得不确定。请帮忙。

1 个答案:

答案 0 :(得分:2)

你必须移动这个

constructor(props) {
  super(props);
  this.state = {showLoading: true};
}

到您的<Table />组件,否则您可以从showLoading访问<Table />'s props,但不会从任何地方传递。{/ p>

然后改变

{ this.props.showLoading ? <Spinner /> : null }

{ this.state.showLoading ? <Spinner /> : null }

要显示/隐藏<Spinner />,只需在this.setState({ showLoading: Boolean })组件中拨打<Table />