简体   繁体   English

使用 react,如何在单击时隐藏表格行?

[英]Using react, how would I hide a table row on click?

Hey guys I am using this table to display data and I added a button to each row.嘿伙计们,我正在使用此表来显示数据,并为每一行添加了一个按钮。 How would I be able to hide a row when I click the hide button next to it?单击旁边的隐藏按钮时,如何隐藏一行?

I am aware of a way to do within html elements but not sure how to hide a particular row within a table thats within a loop我知道一种在 html 元素中执行的方法,但不确定如何在循环内的表中隐藏特定行

Can anyone show me how to accomplish this?谁能告诉我如何做到这一点?

Thank you谢谢

import React, { Component } from 'react'

class Table extends Component {
   constructor(props) {
      super(props) //since we are extending class Table so we have to use super in order to override Component class constructor
      this.state = { //state is by default an object
         students: [
            { id: 1, name: 'Wasif', age: 21, email: 'wasif@email.com' },
            { id: 2, name: 'Ali', age: 19, email: 'ali@email.com' },
            { id: 3, name: 'Saad', age: 16, email: 'saad@email.com' },
            { id: 4, name: 'Asad', age: 25, email: 'asad@email.com' }
         ]
      }
   }

   renderTableData() {
    return this.state.students.map((student, index) => {
       const { id, name, age, email } = student //destructuring
       return (
          <tr key={id}>
             <td>{id}</td>
             <td>{name}</td>
             <td>{age}</td>
             <td>{email}</td>
             <td><button>HIDE</button></td>
          </tr>
       )
    })



 }
renderTableHeader() {
      let header = Object.keys(this.state.students[0])
      return header.map((key, index) => {
         return <th key={index}>{key.toUpperCase()}</th>
      })
   }







   render() { //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
    return (
      <div>
         <h1 id='title'>React Dynamic Table</h1>
         <table id='students'>
            <tbody>
               <tr>{this.renderTableHeader()}</tr>
               {this.renderTableData()}
            </tbody>
         </table>
      </div>
   )
}
}

export default Table 
Try this code

import React, { Component } from "react";

class Table extends Component {
  constructor(props) {
    super(props); //since we are extending class Table so we have to use super in order to override Component class constructor
    this.state = {
      //state is by default an object
      students: [
        { id: 1, name: "Wasif", age: 21, email: "wasif@email.com", toggle: true},
        { id: 2, name: "Ali", age: 19, email: "ali@email.com", toggle: true },
        { id: 3, name: "Saad", age: 16, email: "saad@email.com", toggle: true},
        { id: 4, name: "Asad", age: 25, email: "asad@email.com", toggle: true }
      ]
    };
  }
  handleClick(index) {
    let students = [...this.state.students];
    students[index].toggle = !students[index].toggle;
    this.setState({ students });
  }
  renderTableData() {
    return this.state.students.map((student, index) => {
      const { id, name, age, email, toggle } = student; //destructuring
      if (toggle) {
        return (
          <tr key={id}>
            <td>{id}</td>
            <td>{name}</td>
            <td>{age}</td>
            <td>{email}</td>
            <`td`>
              <button
                value={index}
                onClick={(e) => this.handleClick(e.target.value)}
              >
                Hide
              </button>
            </td>
          </tr>
        );
      } else {
        return null;
      }
    });
  }
  renderTableHeader() {
    let header = Object.keys(this.state.students[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  }

  render() {
    //Whenever our class runs, render method will be called automatically, it may have already defined in the constructor behind the scene.
    return (
      <div>
        <h1 id="title">React Dynamic Table</h1>
        <table id="students">
          <tbody>
            <tr>{this.renderTableHeader()}</tr>
            {this.renderTableData()}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Table;

Add a isVisible key in all objects like在所有对象中添加一个 isVisible 键,例如

 students: [
            { id: 1, name: 'Wasif', age: 21, email: 'wasif@email.com', isVisible: true },
            { id: 2, name: 'Ali', age: 19, email: 'ali@email.com', isVisible: true },
            { id: 3, name: 'Saad', age: 16, email: 'saad@email.com', isVisible: true },
            { id: 4, name: 'Asad', age: 25, email: 'asad@email.com', isVisible: true }
         ]

Then in your render row function do this然后在您的渲染行函数中执行此操作

renderTableData() {
    return this.state.students.map((student, index) => {
       const { id, name, age, email, isVisible } = student
       return isVisible ? (
          <tr key={id}>
             <td>{id}</td>
             <td>{name}</td>
             <td>{age}</td>
             <td>{email}</td>
             <td><button>HIDE</button></td>
          </tr>
       ) : null
    })

On button/row click update state.在按钮/行上单击更新状态。

You could add an onClick handler to the button that adds a property that determines the student should be hidden or not.您可以向button添加一个onClick处理程序,该处理程序添加一个属性,该属性确定是否应该隐藏student

Notice the onClick={() => this.hideRow(id)} below.注意下面的onClick={() => this.hideRow(id)}

renderTableData() {
  return this.state.students.map((student, index) => {
    const { id, name, age, email, isHidden } = student; //destructuring

    // isHidden will default to undefined if not found on the student object
    
    // user is hidden
    if (isHidden === true) {
      return null;
    }

    return (
      <tr key={id}>
        <td>{id}</td>
        <td>{name}</td>
        <td>{age}</td>
        <td>{email}</td>
        <td>
          <button onClick={() => this.hideRow(id)}>HIDE</button>
        </td>
      </tr>
    );
  });
}

The hideRow method will accept a student id and will add an isHidden: true attribute to the student with that id . hideRow方法将接受一个学生id并将向具有该id的学生添加一个isHidden: true属性。

hideRow(id) {
  const students = this.state.students.map((student) => {
    // not same id? leave as is
    if (student.id !== id) {
      return student;
    }

    return { ...student, isHidden: true };
  });

  this.setState({ students });
}

Now you don't want to display the isHidden column, so you have to update renderTableHeader method to skip that.现在您不想显示isHidden列,因此您必须更新renderTableHeader方法以跳过它。

renderTableHeader() {
  let header = Object.keys(this.state.students[0]);
  return header.map((key, index) => {
   
    // notice this
    if (key === "isHidden") {
      return null;
    }

    return <th key={index}>{key.toUpperCase()}</th>;
  });
}

编辑沉思樱桃y7i5c

Follow these steps:按着这些次序:

  1. Put an onclick on the button在按钮上单击
  2. Pass the array as props to the component将数组作为道具传递给组件
  3. On the next component display the array在下一个组件上显示数组
  4. Add the onclick method to it which is also passed as a props from the main component(Pass id as a parameter)向其中添加 onclick 方法,该方法也作为来自主要组件的道具传递(将 id 作为参数传递)
  5. In the method use a filter array to remove the row of your choice when you click it.在该方法中,当您单击它时,使用过滤器数组删除您选择的行。 The code is as follow:代码如下:

https://codesandbox.io/s/modern-tdd-mlmzl?file=/src/components/Table.js https://codesandbox.io/s/modern-tdd-mlmzl?file=/src/components/Table.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM