English 中文(简体)
• 如何在表格中添加检查箱——修订
原标题:How to add checkbox to table -React

我想在表一中增加一个核对箱。 此外,应当有一个独一无二的州,它应当能够选择所有各行。 我已尝试过这项工作,但所有部分都做了工作。


import React, { useState, useEffect } from  react ;

const UserTable = props => {

    const [users , setUsers] = useState([]) ;
    const userData = [props.users] ;

    useEffect(() => {
        setUsers(userData)
    },[]) ;

    const handleChange = (e) => {
        const {name , checked} = e.target ;

        if(name === "allSelect") {
            let tempUser = users.map(user => {
                return {...user,isChecked: checked}
            }) ;
            setUsers(tempUser) ;
        }
        else { 
            let tempUser = users.map(user => user.name === name ? {...user, isChecked: checked} : users);

            setUsers(tempUser) ;
        }
    }


    return (
        <table className="table table-dark">
            <thead>
                
                <tr>
                <th scope="col">
                    <input
                        type="checkbox"
                        className="form-check-input"
                        name = "allSelect"
                        onChange = {handleChange}
                    />Select All
                </th>
                    <th scope="col">Hostname</th>
                    <th scope="col">Username</th>
                    <th scope="col">Stop</th>
                    <th scope="col">Sleep</th>
                    <th scope="col">Start</th>
                    <th scope="col">Status</th>
                    <th scope="col">CPU Temperature(°C)</th>
                    <th scope="col">GPU Info</th>
                    <th scope="col">Edit/Delete</th>
                </tr>
            </thead>


            <tbody>
                {

                    props.users.length > 0 ? (
                        props.users.map(user => (

                            <tr key={user.id}>

                                <th scope="row">
                                    <input
                                        type="checkbox"
                                        className="form-check-input"
                                        checked = {user?.isChecked || false}
                                        onChange = {handleChange}
                                    />
                                </th>


                                <td>{user.name}</td>
                                <td>{user.username}</td>
                                <td><button onClick={() => props.editStopPC(user)} className="btn btn-danger">Stop</button></td>
                                <td><button onClick={() => props.editSleepPC(user)} className="btn btn-warning">Sleep</button></td>
                                <td><button onClick={() => props.editStartPC(user)} className="btn btn-success">Start</button></td>
                                <td>{user.status}</td>
                                <td>{user.cpu}</td>

                                <td>{user.info}</td>
                                <td className="center-align">
                                    <button
                                        className="btn btn-info"
                                        onClick={() => props.editRow(user)}>
                                        edit
                                    </button>

                                    <button
                                        className="btn btn-danger"
                                        onClick={() => props.deleteUser(user.id)}>
                                        delete
                                    </button>
                                </td>
                            </tr>
                        ))
                    ) : (
                        <tr>
                            <td colSpan={9}>{props.users[0]} No Users</td>
                        </tr>
                    )
                }
            </tbody>
        </table>
    )
};

export default UserTable;


I m 获取支持实验性合成纤维链条目前使错误成为可能。 关于<条码:用户? 用户:虚假的,但还是没有工作。 如果你帮助,我很高兴。

EDIT:

const [selected , setSelected] = useState([]) ;
    const userData = [props.users] ;

    useEffect(() => {
        setSelected(userData)
    },[]) ;

    const handleClick = (event, name) => {
        const selectedIndex = selected.indexOf(name);
        let newSelected = [];
        if (selectedIndex === -1) {
          newSelected = newSelected.concat(selected, name);
        } else if (selectedIndex === 0) {
          newSelected = newSelected.concat(selected.slice(1));
        } else if (selectedIndex === selected.length - 1) {
          newSelected = newSelected.concat(selected.slice(0, -1));
        } else if (selectedIndex > 0) {
          newSelected = newSelected.concat(
            selected.slice(0, selectedIndex),
            selected.slice(selectedIndex + 1)
          );
        }
        setSelected(newSelected);
      };

<th scope="col">
                    <input
                        type="checkbox"
                        className="form-check-input"
                        name = "allSelect"
                        checked={isItemSelected}
                        onChange={(event) => handleClick(event, this.name)}
                    />Select All

                </th>

如果你再次谈论采用这一方式,我就错了<代码>。 是 选定的项目没有界定“无<>/代码”。

问题回答
<Checkbox checked={isItemSelected} onChange={(event) => handleClick(event, name)} />

而这一职能是:

  const handleClick = (event, name) => {
    const selectedIndex = selected.indexOf(name);
    let newSelected = [];
    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, name);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
        selected.slice(0, selectedIndex),
        selected.slice(selectedIndex + 1)
      );
    }
    setSelected(newSelected);
  };

You can check my example here: https://codesandbox.io/p/sandbox/react-table-sr7tr3

Explanation: If you would like to create a table in React from scratch, without using any external library, I would suggest the following: Initialize the state of your table with an array. If it is possible, make sure that every object in you array has a "checked" or "selected" etc. property. Add a handler function to your table. When you click on the "Select all" button or checkbox, the handler function should update the initial state: map through the initial array, copy the content of the element, then assign the boolean true to the "checked" or "selected" whatever... property.





相关问题
ASP.NET checkbox changes focus?

I have a checkbox control, and when it s clicked, the focus of the page changes to the top--the window scrolls to the top of the page. Nowhere in the code am I specifying a change in focus, either in ...

ASP.Net MVC - Handle Multiple Checkboxes

Ok, I have a role based permission system in place and would like admin s to be able to edit the permissions for each role. To do this I need to load lots of checkboxes, however I m struggling with ...

checkbox / div toggle

$(".trigger").click(function () { $(this).next(".toggle").slideToggle("fast"); $(this).toggleClass("active"); return false }); HTML: <input type="checkbox" class="trigger"> <div class=...

sticky checkbox

Ii am trying to make a checkbox (to send via email) sticky. To make sure it doesn t make a problem when sent empty I used the following: <input type="checkbox" name="something" value="1"> <...

Tri-state Check box in HTML?

There is no way to have a tri-state check button (yes, no, null) in HTML, right? Are there any simple tricks or work-arounds without having to render the whole thing by oneself?

How to get unselected checkbox?

I have three checkboxes like ch[0], ch[1] and ch[3] (sometimes i have more, or less, it s dinamic) and in PHP i want to get the unselected items also, like this: 0=yes,1=no,3=yes and so on. Can I ...

热门标签