简体   繁体   中英

React. Editeble table

Immediately apologize for my English.

In the table opposite each row there should be an “edit” button, when you click on it, all cells in the row become editable, and instead of the “edit” button, the “save” button appears. I spent a lot of time and just can't figure it out.

I need to release without react tables, react grid etc.

My table:

        <table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Username</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            {props.items.map(item => (
                    <tr key={item.id}>
                        <td>{item.data.name}</td>
                        <td>{item.data.surname}</td>
                        <td>{item.data.age}</td>
                        <td>
                            <button onClick>Edit</button> //need to improve this button

                            <button onClick={() => removeID(user.id)}>Delete</button>

                        </td>
                    </tr>
                ))}
            </tbody>
        </table>
    )

I would suggest is you save a state for specifying if the current table is on edit mode or not. This could be as simple as setting the initial state as { editMode: false } and you would create an onClick handler on your button that would set the state of editMode to true , (I can't tell from the example if you are going to use hooks or not so simply look into how you would change the said state).

Now, having that state, you could do this <button onClick={this.toggleEditMode}>{ editMode ? "Save" : "Edit" }</button> <button onClick={this.toggleEditMode}>{ editMode ? "Save" : "Edit" }</button> , if editMode is true , then show Save else Edit

For the cells to be editable, that's another problem entirely but the approach I would suggest is to utilize the editMode state, change the value of the tds with inputs with the same approach above then you have to attach onChange handlers that would update the items props. Just a matter of figuring out which item to update in which that key prop will help you do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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