🥹Thuộc tính ref có tiện ích vô cùng lớn (ok)

Có thể sử dụng trực tiếp trong form mà không phải khai báo gì 👇

src\Context.tsx

import React, { createContext } from 'react'
export const AppContext:any = createContext(null);
export const Provider:any = AppContext.Provider;

src\components\listUserComponent.jsx

import React, { Component } from 'react';
import axios from 'axios';
import { AppContext } from '../Context';
class listUserComponent extends Component {
  static contextType = AppContext;
  handleUpdate = (id) => {
    this.context.handleUpdate(id, this.name.value, this.email.value);
  }
  render() {
    var { users } = this.context;
    var allUsers = users?.map(({ id, user_name, user_email, isEditing }) => {
      return isEditing === true ? (
        (
          <tr key={id}>
            <td><input className="form-control" type="text" ref={(item) => this.name = item} defaultValue={user_name} /></td>
            <td><input className="form-control" type="email" ref={(item) => this.email = item} defaultValue={user_email} /></td>
            <td>
              <button className="btn btn-success mr-2" onClick={() => this.handleUpdate(id)}>Save</button>
              <button onClick={() => this.context.cancelEdit(id)} className="btn btn-light">Cancel</button>
            </td>
          </tr>
        )
      ) : (
        <tr key={id}>
          <td>{user_name}</td>
          <td>{user_email}</td>
          <td>
            <button className="btn btn-dark mx-2" onClick={() => this.context.editMode(id)}>Edit</button>
            <button className="btn btn-danger" onClick={() => this.context.handleDelete(id)}>Delete {id}</button>
          </td>
        </tr>
      );
    });
    return (
      <div className="col-md-8">
        <table className="table table-striped table-bordered">
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {allUsers}
          </tbody>
        </table>
      </div>
    );
  }
}
export default listUserComponent;

Last updated

Was this helpful?