如何访问一个组件的状态或另一个组件(非父子组件)中一个组件的常量-React

时间:2018-12-10 03:20:59

标签: reactjs react-table

我正在研究React Table。我基本上是React的初学者。我有一个仪表板页面,其中显示8列的React Table。我有一个自定义按钮,它将打开一个弹出页面,此弹出页面有8个复选框,可让我显示/隐藏那些React列。最初,此弹出页面中的所有复选框均设置为true。当我取消选中某个列时,该特定列将被禁用。

Image

这是复选框弹出页面的代码

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { ActionCreators } from '../../../actions';
import ButtonComponent from '../../common/button/ButtonComponent';
import { CheckBox } from '../../common/chkbox/CheckBox';

class CustomizedView extends Component {
  constructor(props) {
    super(props);
    this.handleCheckChildElement = this.handleCheckChildElement.bind(this);
    this.state = {
      items: [
        { id: 1, value: 'Column 1', isChecked: true },
        { id: 2, value: 'Column 2', isChecked: true },
        { id: 3, value: 'Column 3', isChecked: true },
        { id: 4, value: 'Column 4', isChecked: true },
        { id: 5, value: 'Column 5', isChecked: true },
        { id: 6, value: 'Column 6', isChecked: true },
        { id: 7, value: 'Column 7', isChecked: true },
        { id: 8, value: 'Column 8', isChecked: true },
      ]
    };
  }

  handleClick() {
    this.setState({ isChecked: !this.state.isChecked });
  }

  handleCheckChildElement(event) {
    const { items } = this.state; //extract state values like this to a const variable
    const newItems = items.map((item) => { //do map on items because map returns a new array. It’s good practice to use .map than forEach in your case
      if(item.value === event.target.value) {
        item.isChecked = event.target.checked;
        return item; //return updated item object so that it will be pushed to the newItems array
      }
      return item; // return item because you need this item object as well
    });
    this.setState({ items: newItems }); //finally set newItems array into items
    const column1checked = items[0].isChecked;
    console.log('column1checked ' + column1checked);
    const column2checked = items[1].isChecked;
    console.log('column2checked ' + column2checked);
    const column3checked = items[2].isChecked;
    console.log('column3checked ' + column3checked);
    const column4checked = items[3].isChecked;
    console.log('column4checked ' + column4checked);
    const column5checked = items[4].isChecked;
    console.log('column5checked ' + column5checked);
    const column6checked = items[5].isChecked;
    console.log('column6checked ' + column6checked);
    const column7checked = items[6].isChecked;
    console.log('column7checked ' + column7checked);
    const column8checked = items[7].isChecked;
    console.log('column8checked ' + column8checked);
  }

  render() {
    return (
      <div className='div-container-custom' >
        <div className='bottomBar'>
          <ButtonComponent
            text='Apply'
            className='activeButton filterMargin-custom'
            width='100'
            display='inline-block'
            onClick={() => { this.props.applyFilter(this.state, false); }}
          />
          <ButtonComponent
            text='Clear Filter'
            className='greyedButton clear-custom-filter'
            width='100'
            display='block'
            marginTop='60'
            onClick={() => { this.props.applyFilter(this.state, true); }}
          />
        </div>
        <div>
          <div className='data-points-text'>
            <span> Columns </span>
          </div>
          <div className="App">
            <ul>
              {
                this.state.items.map((item, i) => {
                  return (<div key={i} ><CheckBox handleCheckChildElement={this.handleCheckChildElement} {...item} /></div>);
                })
              };
            </ul>
          </div>
        </div>
      </div>
    );
  }
}

CustomizedView.propTypes = {
  applyFilter: PropTypes.func.isRequired
};

CustomizedView.defaultProps = {
};

function mapStateToProps(state) {
  return {
    auth: state.auth
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(ActionCreators, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(CustomizedView);

我是React的入门者,我需要这个社区的帮助。请帮助实现这个想法。

我可以传输常量(是/否)还是应该传输状态。我想将每个列的布尔值从components \ abcdashboard \ customized_view \ Customizedview转移到components \ common \ react_table \ ReactTableComponent

请仔细看。注意

之后的行
this.setState({ items: newItems });

我尝试导出常量,但出现错误。我认为React不允许我们导出常量。如果我转移状态,应该如何从components \ abcdashboard \ customized_view \ Customizedview到components \ common \ react_table \ ReactTableComponent

提取状态

应注意,此组件不是父级-子级。您可以检查文件路径。

作为初学者,我对Redux一无所知。虽然我有Redux连接,但是我不知道如何使用它。那么如何从components \ common \ react_table \ ReactTableComponent的components \ abcdashboard \ customized_view \ Customizedview中访问状态

export default connect(mapStateToProps, mapDispatchToProps)(CustomizedView);

所以我有mapStateToProps和mapDispatchToProps函数

function mapStateToProps(state) {
  return {
    auth: state.auth
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(ActionCreators, dispatch);
}

我只需要将8个标志/布尔值从components \ abcdashboard \ customized_view \ Customizedview转移到components \ common \ react_table \ ReactTableComponent

1 个答案:

答案 0 :(得分:0)

因此,您可以通过两种方式实现用例。我将使用state / props对此进行解释,并出于两个原因避免使用Redux:
首先,您提到您是Redux的初学者,所以不想让您更加困惑。但是更重要的是,想要向您展示比没有Redux可以实现的更多的事情。 我将用代码片段解释该理论,但是实现仍将留给您。

假设您有一个名为App的组件。这将托管您的Customizedview + ReactTableComponent

从组件甚至您的状态导出const都是反应中的反模式。
而是将一个道具传递给名为Customizedview的{​​{1}}。

每当复选框更改时,您的onCheckBoxChange都会调用此道具,并返回其上所有复选框的状态。

Customizedview组件会将其存储在名为App的自己的状态中,并将两个checkedItems作为属性传递给它。下面的代码段:

ReactTableComponent

如果您有任何困难,请发表评论。