javascript - 如何将这三个函数全部写在父组件中,而不是写在子组件中 - ReactJS

标签 javascript reactjs

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

Image

现在我已经在子组件中编写了一些功能(3个主要功能)。为了应用程序的简单性,我现在想将这 3 个功能移动到父组件。

这是我的子组件

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


class CustomizedViewInv extends Component {
  constructor(props) {
    super(props);
    this.handleCheckChildElement = this.handleCheckChildElement.bind(this);
    // this.applyFilter = this.applyFilter.bind(this);
    this.resetFilter = this.resetFilter.bind(this);
    this.state = {
      items: this.props.items,
    };
  }

  getCheckBox(item) {
    return (
      <div>
        <input
          value={item.id}
          // className='chkProd'
          type='checkbox'
          checked={item.isChecked}
          //disabled={d.poId !== null || d.status !== 'Responded'}
          onClick={(e) => { this.handleCheckChildElement(e); }}
        />
        {item.value}
      </div>);
  }

  handleCheckChildElement(event) {
    const { items } = this.state;
    for (let i = 0; i < items.length; i = i + 1) {
      if(items[i].id === +event.target.value) {
        items[i].isChecked = !items[i].isChecked;
        break;
      }
    }
    this.setState({ items });
  }

  resetFilter() {
    const { items } = this.state;
    for (let i = 0; i < items.length; i = i + 1) {
      items[i].isChecked = true;
    }
    this.setState({ items });
    console.log('Reset filter : > Items : ' + JSON.stringify(items));
  }

  render() {
    const { items } = this.state;
    return (
      <div className='dashboardFilter-container' >
        <div className='bottomBar'>
          <ButtonComponent
            text='Apply'
            className='activeButton filterMargin-div'
            width='100'
            display='inline-block'
            // onClick={() => { this.props.applyFilter(); }}
          />
          <ButtonComponent
            text='Reset'
            className='greyedButton clear-dashboard-filter'
            width='100'
            display='block'
            marginTop='60'
            onClick={() => { this.resetFilter(); }}
          />
        </div>
        <div>
          <div className='data-points-text'>
            <span> Columns </span>
          </div>
          <div className="App">
            {items.map((item) => {
                return this.getCheckBox(item);
            })}
          </div>
        </div>
      </div>
    );
  }
}

CustomizedViewInv.propTypes = {
  items: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
};

CustomizedViewInv.defaultProps = {
};

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

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

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

在我的父组件中,我导入了子组件。你可以在 Child Component 中看到一个名为 items 的 proptype。

基本上在父组件的状态下,我有一个名为 filterItems 的对象

filterItems: [
        { id: 1, value: 'Col 1', isChecked: true },
        { id: 2, value: 'Col 2', isChecked: true },
        { id: 3, value: 'Col 3', isChecked: true },
        { id: 4, value: 'Col 4', isChecked: true },
        { id: 5, value: 'Col 5', isChecked: true },
        { id: 6, value: 'Col 6', isChecked: true },
        { id: 7, value: 'Col 7', isChecked: true },
        { id: 8, value: 'Col 8', isChecked: true },
        { id: 9, value: 'Col 9', isChecked: true },
        { id: 10, value: 'Col 10', isChecked: true },
      ],
      isCustomizedOpen: false,

现在我基本上是这样调用Child

{this.state.isCustomizedOpen &&
          <CustomizedViewInv
            items={filterItems}
          />}

请告诉我如何将这 3 个函数 - getCheckBox、handleCheckChildElement 和 resetFilter 从子页面移动到父页面。

我基本上是 React 的初学者。因此,请帮助我了解将这 3 个函数 - getCheckBox、handleCheckChildElement 和 resetFilter 从子页面移动到父页面需要进行哪些更改。

最佳答案

试试这个方法;让你的容器对组件有更多的控制权 working example

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

const Button = props => {
  return <button onClick={() => props.onClick()}>{props.text}</button>;
};

export default class App extends React.Component {
  state = {
    filterItems: [
      { id: 1, value: "Col 1", isChecked: true },
      { id: 2, value: "Col 2", isChecked: true },
      { id: 3, value: "Col 3", isChecked: true },
      { id: 4, value: "Col 4", isChecked: true },
      { id: 5, value: "Col 5", isChecked: true },
      { id: 6, value: "Col 6", isChecked: true },
      { id: 7, value: "Col 7", isChecked: true },
      { id: 8, value: "Col 8", isChecked: true },
      { id: 9, value: "Col 9", isChecked: true },
      { id: 10, value: "Col 10", isChecked: true }
    ]
  };
  handleCheckChildElement(e) {
    alert(e.target.value);
  }
  resetFilter() {
    alert("resetFilter");
  }
  applyFilter() {
    alert("applyFilter");
  }
  render = () => {
    return (
      <div>
        {this.state.filterItems.map(item => (
          <CheckBox
            item={item}
            handleCheckChildElement={this.handleCheckChildElement.bind(this)}
          />
        ))}
        <Button text="Reset" onClick={this.resetFilter.bind(this)} />
        <Button text="Apply" onClick={this.applyFilter.bind(this)} />
      </div>
    );
  };
}

关于javascript - 如何将这三个函数全部写在父组件中,而不是写在子组件中 - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53794112/

相关文章:

php - Facebook 连接 : Error when clicking the Facebook Connect button

JavaScript 混排算法解释

javascript - Jquery 对话无法正常工作

reactjs - ReactGA 不适用于 G 类型跟踪 ID

javascript - mouseover mouseout JQuery 时自动播放/暂停

javascript - 我可以使用 Passportjs 仅对某些 google 用户进行身份验证吗?

reactjs - 推特卡 - "WARN: No metatags found"

javascript - React 使用 switch 语句有条件地显示图像不起作用

node.js - React 连接到 API,无需生产环境中的端点

android - react native fbsdk 问题 - 任务 :react-native-fbsdk:compileDebugJavaWithJavac FAILED