react-redux如何使用输入编辑表格

时间:2019-04-27 19:13:43

标签: reactjs react-redux

im在react和redux中使用模式来编辑数据,im使用输入而不是按钮,因为我需要验证模式中的字段,因此我无法使用按钮可以使用的data-dismiss =“ modal”属性。表单在验证,提交和数据编辑方面都可以正常工作,但是因为我无法使用data-dismiss =“ modal”,所以我单击编辑输入后浏览器的背景变暗了,因为我没有执行data-dismiss =“模态”属性(类似于模态仍处于打开状态)

试图使用按钮代替输入表单,但我不能正确使用验证

UsersManagement.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from './common/Spinner';
import { getUsers } from '../actions/userActions';
import { Link } from 'react-router-dom';
import Modal from './modal/Modal';

class UsersManagement extends Component {
  constructor(props) {
    super(props);
    this.state = {
      requiredItem: 1
    }
  }

  replaceModalItem = index => {
    this.setState({
      requiredItem: index
    });
  }

  componentDidMount() {
    if (!this.props.auth.isAuthenticated) {
      this.props.history.push('/login');
    }
    this.props.getUsers();
  }

  render() {
    const { users, loading } = this.props.user;
    let usersList;
    let userModal;
    if (users === null || loading) {
      usersList = <tr><td colSpan="4"><Spinner /></td></tr>
    } else {
      if (users.length > 0) {
        const requiredItem = this.state.requiredItem;
        let modalData = users[requiredItem];
        userModal = <Modal
          username={modalData.username}
          firstName={modalData.firstName}
          lastName={modalData.lastName}
          email={modalData.email}
          phone={modalData.phone}
          id={modalData._id}
        />
        usersList = users.map((user, index) => (
          <tr key={index}>
            <th scope="row">
              <button data-toggle="modal" data-target="#exampleModal"
                onClick={() => this.replaceModalItem(index)} type="button"
                className="btn btn-primary fa-xs mr-1"><i className="fas fa-pencil-alt"></i></button>
              <button type="button" className="btn btn-danger fa-xs"><i className="far fa-trash-alt"></i></button>
            </th>
            <td>{user.username}</td>
            <td>{user.email}</td>
            <td>{user.phone}</td>
          </tr>
        ))
      } else {
        usersList = <h2>No users</h2>
      }
    }

    return (
      <div className="row">
        <div className="col-12">
          <h1 className="text-center mb-2">Users Management</h1>
          <Link to="/add-user" className="btn btn-success mb-4">New User</Link>
          <table className="table">
            <thead>
              <tr>
                <th scope="col">Options</th>
                <th scope="col">Username</th>
                <th scope="col">Email</th>
                <th scope="col">Phone Number</th>
              </tr>
            </thead>
            <tbody>
              {(usersList)}
            </tbody>
          </table>
          {(userModal)}
        </div>
      </div>
    )
  }
}

UsersManagement.propTypes = {
  getUsers: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
  auth: state.auth,
  user: state.user
})

export default connect(mapStateToProps, {
  getUsers
})(UsersManagement);

Modal.js:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { editUser } from '../../actions/userActions';
import { withRouter } from 'react-router-dom';
import classnames from 'classnames';

class Modal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      username: '',
      firstName: '',
      lastName: '',
      email: '',
      phone: '',
      errors: {}
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      id: nextProps.id,
      username: nextProps.username,
      firstName: nextProps.firstName,
      lastName: nextProps.lastName,
      email: nextProps.email,
      phone: nextProps.phone
    });

    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors })
    }
  }

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  }

  onSubmit = e => {
    e.preventDefault();

    const userData = {
      username: this.state.username,
      firstName: this.state.firstName,
      lastName: this.state.lastName,
      email: this.state.email,
      phone: this.state.phone
    }
    this.props.editUser(this.state.id, userData, this.props.history);
  }

  render() {
    const { errors } = this.state;
    return (
      <div className="modal fade" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="exampleModalLabel">Edit User</h5>
              <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <form onSubmit={this.onSubmit} noValidate>
              <div className="modal-body">
                <p><span className="modal-lable">Username : </span>
                  <input type="text" name="username" value={this.state.username} onChange={this.onChange}
                    error={errors.username} className={classnames("form-control mt-2", {
                      'is-invalid': errors.username
                    })} />{errors.username && (<span className="invalid-feedback">{errors.username}</span>)}</p>
                <p><span className="modal-lable">First name : </span>
                  <input type="text" name="firstName" value={this.state.firstName} onChange={this.onChange}
                    error={errors.firstName} className={classnames("form-control mt-2", {
                      'is-invalid': errors.firstName
                    })} />{errors.firstName && (<span className="invalid-feedback">{errors.firstName}</span>)}</p>
                <p><span className="modal-lable">Last name : </span>
                  <input type="text" name="lastName" value={this.state.lastName} onChange={this.onChange}
                    error={errors.lastName} className={classnames("form-control mt-2", {
                      'is-invalid': errors.lastName
                    })} />{errors.lastName && (<span className="invalid-feedback">{errors.lastName}</span>)}</p>
                <p><span className="modal-lable">Email : </span>
                  <input type="email" name="email" value={this.state.email} onChange={this.onChange}
                    error={errors.email} className={classnames("form-control mt-2", {
                      'is-invalid': errors.email
                    })} />{errors.email && (<span className="invalid-feedback">{errors.email}</span>)}</p>
                <p><span className="modal-lable">Phone : </span>
                  <input type="tel" name="phone" value={this.state.phone} onChange={this.onChange}
                    error={errors.phone} className={classnames("form-control mt-2", {
                      'is-invalid': errors.phone
                    })} />{errors.phone && (<span className="invalid-feedback">{errors.phone}</span>)}</p>
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" data-dismiss="modal" >Close</button>
                <input type="submit" name="submit" value="Save Changes" className="btn btn-primary" />
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

Modal.propTypes = {
  editUser: PropTypes.func.isRequired,
  user: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
  user: state.user,
  errors: state.errors,
})

export default connect(mapStateToProps, {
  editUser
})(withRouter(Modal));

我该如何解决这个问题?

0 个答案:

没有答案