如何访问另一个组件中一个组件的常量变量-React

时间:2018-12-09 17:52:23

标签: javascript reactjs react-table

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

最后有图像可以看到我要做什么。

我将使用此逻辑显示隐藏列(这个问题是我两天前问过的)-You can see how this is done using a React Table attribute/property called show。如果显示为true,则显示列/子列;如果显示为false,则隐藏列/子列。

React Table数据是这样的

const columns = [
 {
    Header: 'Column 1',
    accessor: 'firstName',
    // show: true // shows the particular column (true is default)
   //  show: false // hides the particular column
  },
  {
    Header: 'Column 2',
    accessor: 'firstName',
  },
  {
    Header: 'Column 3',
    accessor: 'firstName',
  },
  {
    Header: 'Column 4',
    accessor: 'firstName',
  },
  {
    Header: 'Column 5',
    accessor: 'firstName',
  },
  {
    Header: 'Column 6',
    accessor: 'firstName',
  },
  {
    Header: 'Column 7',
    accessor: 'firstName'
  },
  {
    Header: 'Column 8',
    accessor: 'firstName',
  }
];

现在看看这张图片。该图像显示了我的仪表板页面以及复选框弹出页面,可以打开/关闭(或显示/隐藏)我的列

Image of dashboard and checkbox page

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

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);

现在我的意思是,当我仅取消选中复选框弹出页面中的第4列时,我会得到所需的值(上面的代码)

column1checked true
column2checked true
column3checked true
column4checked false
column5checked true
column6checked true
column7checked true
column8checked true

最终这是我的复选框页面

import React from 'react';
import PropTypes from 'prop-types';

export const CheckBox = (props) => {
  // super(props);
  return (
    <li>
      <input key={props.id} onClick={props.handleCheckChildElement} type="checkbox" checked={props.isChecked} value={props.value} /> {props.value}
    </li>
  );
};

CheckBox.propTypes = {
  id: PropTypes.string,
  handleCheckChildElement: PropTypes.func,
  isChecked: PropTypes.bool,
  value: PropTypes.string,
};

export default CheckBox;

现在我的问题是我在CustomizedView Component中有常量。我需要那些在ReactTable组件中可用的const变量(路径是这样的-'../../ common / chkbox / CheckBox')

在主仪表板页面中,导入React Table

import ReactTableComponent from '../common/react_table/ReactTableComponent';

并以这种方式在仪表板主页面的渲染功能中使用它。

<ReactTableComponent />

所以我需要使用ReactTable组件中所有Customized变量的const变量来显示/隐藏表。

在这里我还必须使用show:some_const(我不能使用true或false)

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

我想知道将这8个const变量从components \ abcdashboard \ customized_view \ Customizedview转移到components \ common \ react_table \ ReactTableComponent的最好/最简单的方法(也许是很棒的方法或愚蠢的方法)

1 个答案:

答案 0 :(得分:1)

通常,当您想要在像这样的组件之间共享数据时,您想要的是将数据合并到上层组件中,并使用函数对其进行修改。

这是一个人为的示例(CodeSandbox here):

import React from "react";
import ReactDOM from "react-dom";

class Parent extends React.Component {
  state = {
    name: "Bill"
  };

  changeName = name => {
    this.setState({ name });
  };

  render() {
    return (
      <React.Fragment>
        <h1>name is: {this.state.name}</h1>
        <ChildA changeName={this.changeName} />
        <ChildB changeName={this.changeName} />
      </React.Fragment>
    );
  }
}

class ChildA extends React.Component {
  state = {
    nameA: "Steve"
  };

  render() {
    return (
      <button onClick={() => this.props.changeName(this.state.nameA)}>
        change to my name
      </button>
    );
  }
}

class ChildB extends React.Component {
  state = {
    nameB: "Elon"
  };

  render() {
    return (
      <button onClick={() => this.props.changeName(this.state.nameB)}>
        change to my name
      </button>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);

在这里,Parent可以通过向下传递的changeName函数访问子代名称的值。

如果您只想共享变量而不是数据本身,则可以只定义一个完整的文件并导出各种变量,例如:

export const PI = 3.14

依此类推,然后执行以下操作:

import { PI } from './variables'
例如,在其他文件中