簡體   English   中英

ReactJS 模態組件不會關閉 onclick

[英]ReactJS Modal component won't close onclick

我創建了一個鏈接到 reactJs 前端的用戶 CRUD api。 我一直在使用引導程序組件並決定使用模態組件來編輯表單。 唯一的問題是,由於某種原因,當模式打開時,除非我重新加載瀏覽器,否則我無法再次退出它。

EditUserModal.js 的代碼如下:

import React, { Component } from 'react';
import {Modal, Button, Row, Col, Form} from 'react-bootstrap';
import * as moment from 'moment';

const BASE_API_URL = `http://localhost:56062/api/users`;

var currentDate = new Date();



export class EditUserModal extends Component{
    constructor(props){
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }



    componentDidMount(){
      }

    handleSubmit(event){
        event.preventDefault();
        fetch(BASE_API_URL,{
            method:'PUT',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({

                Id: event.target.Id.value,
                firstName: event.target.firstName.value,
                lastName: event.target.lastName.value,
                Email: event.target.Email.value,
                mobileNumber: event.target.mobileNumber.value,
                dateOfBirth: event.target.dateOfBirth.value,
                lastModified: currentDate
            })
        })
        .then(res=> res.json())
        .then((result) =>
        {
            console.log(result);
        },
        (error) => {
            console.log('Failed')
        }
        )
    }

    render(){
        return(

            <Modal
            {...this.props}
            size="lg"
            aria-labelledby="contained-modal-title-vcenter"
            centered
          >
            <Modal.Header closeButton>
              <Modal.Title id="contained-modal-title-vcenter">
                Edit User
              </Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <div className="editFormContainer">
                  <Row>
                      <Col sm={12}>
                          <Form onSubmit={this.handleSubmit}>

                          <Form.Group controlId="Id">
                                <Form.Label>User ID</Form.Label>
                                <Form.Control name="Id" disabled defaultValue = {this.props.userid} type="text" placeholder="Id" />
                              </Form.Group>
                              <Form.Group controlId="firstName">
                                <Form.Label>First Name</Form.Label>
                                <Form.Control name="firstName" required  type="text" defaultValue = {this.props.firstname} placeholder="First Name" />
                              </Form.Group>
                              <Form.Group controlId="lastName">
                                <Form.Label>Last Name</Form.Label>
                                <Form.Control name="lastName" required type="text" defaultValue = {this.props.lastname} placeholder="Last Name"  />
                              </Form.Group>
                              <Form.Group controlId="Email">
                                <Form.Label>Email address</Form.Label>
                                <Form.Control name="Email" required type="email" defaultValue = {this.props.useremail} placeholder="Email e.g. name@example.com" />
                              </Form.Group>
                              <Form.Group controlId="mobileNumber">
                                <Form.Label>Mobile Number</Form.Label>
                                <Form.Control name="mobileNumber" required type="text" defaultValue = {this.props.mobilenumber} placeholder="Mobile e.g. 0723218223 or +447236475886" />
                              </Form.Group>
                              <Form.Group controlId="dateOfBirth">
                                <Form.Label>Date of Birth</Form.Label>
                                <Form.Control name="dateOfBirth" required type="date" defaultValue = {moment(new Date(this.props.dateofbirth)).format('YYYY-MM-DD')} placeholder="Date of Birth e.g. 05-02-97" />
                              </Form.Group>
                            <Form.Group>
                                <Button variant="primary" type="submit">Edit User</Button>
                            </Form.Group>

                          </Form>

                      </Col>
                  </Row>
              </div>
            </Modal.Body>
            <Modal.Footer>
              <Button variant="danger" onClick={this.props.onHide}>Close</Button>
            </Modal.Footer>
          </Modal>
        )
    }
}

然后對於使用modal的頁面,相關代碼如下:

export class User extends Component {

    constructor(props){
        super(props);
        this.state = {users:[], addModalShow : false, editModalShow: false}

    }

render(){

    const {users, userid, firstname, lastname, useremail, mobilenumber, dateofbirth, lastmodified} = this.state;
    let addModalClose =() => this.setState({addModalShow:false});
    let editModalClose =() => this.setState({editModalShow:false});

    return(
        <div>
            <ButtonToolbar>
              <Button variant='outline-dark' style={{margin:"auto"}} onClick={()=> this.setState({addModalShow:true})}>
                  Add User
              </Button>
                <AddUserModal show={this.state.addModalShow} onHide={addModalClose} />
              </ButtonToolbar>

        <Table responsive borderless style={{borderRadius:"0.3em"}} striped hover size="sm" variant="dark" className="mt-4">
   <thead>
     <tr>
       <th>Id</th>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Email</th>
       <th>Mobile Number</th>
       <th>Date of Birth</th>
       <th>Last Modified</th>
       <th>Edit</th>
       <th>Delete</th>
     </tr>
   </thead>
   <tbody>
        {users.map(user=> 


          <tr key = {user.Id}>
            <td>{user.Id}</td>
            <td>{user.firstName}</td>
            <td>{user.lastName}</td>
            <td>{user.Email}</td>
            <td>{user.mobileNumber}</td>
            <td>{moment(new Date(user.dateOfBirth)).format('YYYY-MM-DD')}</td>
            <td>{user.lastModified}</td>
            <td>
              <ButtonToolbar>
              <Button className="mr-2" variant="outline-light" onClick={()=> { ReactDOM.render(<EditUserModal show={true} userid={user.Id} firstname={user.firstName} 
              lastname={user.lastName} useremail={user.Email} mobilenumber={user.mobileNumber} dateofbirth={user.dateOfBirth} onHide = {editModalClose}  /> , document.getElementById('root')) }}>
              Edit User
              </Button>
              </ButtonToolbar>
              </td>
              <td>
              <Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button>
              </td>

          </tr>
          )}
   </tbody>
 </Table>

 </div>
    )
}

}

為什么模態沒有正確退出? 或者我有什么辦法可以做到這一點? 單擊關閉模態、取消或 X 按鈕似乎不會關閉模態。

======================== 編輯 ========================== ==============

我意識到,當模態處於該狀態並提交編輯表單時,控制台會顯示來自這段代碼的“失敗”消息,即使當我刷新頁面時,它也成功加載了新的編輯信息。

handleSubmit(event){

        event.preventDefault();
        fetch(BASE_API_URL,{
            method:'PUT',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({

                Id: event.target.Id.value,
                firstName: event.target.firstName.value,
                lastName: event.target.lastName.value,
                Email: event.target.Email.value,
                mobileNumber: event.target.mobileNumber.value,
                dateOfBirth: event.target.dateOfBirth.value,
                lastModified: currentDate
            })
        })
        .then(res=> res.json())
        .then((result) =>
        {
            console.log(result);
        },
        (error) => {
            console.log('Failed')
        }
        )
    }

這是一個草圖......但像這樣:

 export class User extends Component { constructor(props){ super(props); this.state = {users:[], addModalShow : false, editModalShow: false, currentEdited: null} } addModalClose =() => this.setState({addModalShow:false}); editModalClose =() => this.setState({editModalShow:false}); render(){ const {users, currentEdited} = this.state; return( <div> <ButtonToolbar> <Button variant='outline-dark' style={{margin:"auto"}} onClick={()=> this.setState({addModalShow:true})}> Add User </Button> <AddUserModal show={this.state.addModalShow} onHide={this.addModalClose} /> </ButtonToolbar> <Table responsive borderless style={{borderRadius:"0.3em"}} striped hover size="sm" variant="dark" className="mt-4"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Mobile Number</th> <th>Date of Birth</th> <th>Last Modified</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {users.map(user=> <tr key = {user.Id}> <td>{user.Id}</td> <td>{user.firstName}</td> <td>{user.lastName}</td> <td>{user.Email}</td> <td>{user.mobileNumber}</td> <td>{moment(new Date(user.dateOfBirth)).format('YYYY-MM-DD')}</td> <td>{user.lastModified}</td> <td> <ButtonToolbar> <Button className="mr-2" variant="outline-light" onClick={()=> { this.setState({ currentEdited: user, editModalShow: true }); }}> Edit User </Button> </ButtonToolbar> </td> <td> <Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button> </td> </tr> )} </tbody> </Table> <EditUserModal show={this.state.editModalShow} onHide={this.editModalClose} {...currentEdited} /> </div> ) } }

這是因為您已將show prop 硬編碼為true

<EditUserModal show={this.state.editModalShow} {...otherProps} /> 

 export class User extends Component { constructor(props){ super(props); this.state = {users:[], addModalShow : false, editModalShow: false} } render(){ const {users, userid, firstname, lastname, useremail, mobilenumber, dateofbirth, lastmodified} = this.state; let addModalClose =() => this.setState({addModalShow:false}); let editModalClose =() => this.setState({editModalShow:false}); return( <div> <ButtonToolbar> <Button variant='outline-dark' style={{margin:"auto"}} onClick={()=> this.setState({addModalShow:true})}> Add User </Button> <AddUserModal show={this.state.addModalShow} onHide={addModalClose} /> </ButtonToolbar> <Table responsive borderless style={{borderRadius:"0.3em"}} striped hover size="sm" variant="dark" className="mt-4"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Mobile Number</th> <th>Date of Birth</th> <th>Last Modified</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {users.map(user=> <tr key = {user.Id}> <td>{user.Id}</td> <td>{user.firstName}</td> <td>{user.lastName}</td> <td>{user.Email}</td> <td>{user.mobileNumber}</td> <td>{moment(new Date(user.dateOfBirth)).format('YYYY-MM-DD')}</td> <td>{user.lastModified}</td> <td> <ButtonToolbar> <Button className="mr-2" variant="outline-light" onClick={()=> { this.setState({ editShowModal: true }); }}> Edit User </Button> <EditUserModal show={this.state.editModalShow} userid={user.Id} firstname={user.firstName} lastname={user.lastName} useremail={user.Email} mobilenumber={user.mobileNumber} dateofbirth={user.dateOfBirth} onHide={editModalClose} /> </ButtonToolbar> </td> <td> <Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button> </td> </tr> )} </tbody> </Table> </div> ) } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM