【问题标题】:ReactJS Modal component won't close onclickReactJS 模态组件不会关闭 onclick
【发布时间】:2020-01-26 00:25:05
【问题描述】:

我创建了一个链接到 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')
        }
        )
    }

【问题讨论】:

  • 你总是通过 show={true}。你不应该传递 editModalShow 属性而不是 {true} 吗?
  • 当我这样做时,单击模态按钮后我只会得到一个白屏。 @G_S
  • 另外,我现在的方式基本上也给出了白屏,但至少显示了模态形式。但我就是无法退出。
  • 白屏时控制台出现任何错误?
  • @G_S 它说:警告:无法对未安装的组件执行 React 状态更新

标签: javascript reactjs bootstrap-modal react-bootstrap


【解决方案1】:

这是一个草图......但是像这样:

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>
    )
}

}

【讨论】:

  • 模态现在正确关闭,但按钮不会将道具发送到模态打开时显示的表单。
  • 你能用你的代码发送一个沙箱吗?例如codesandbox.io
  • 我实际上在使用你的技术时必须单独设置道具,但现在一切正常
【解决方案2】:

这是因为您已将 show 属性硬编码为 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>
    )
}

}

【讨论】:

  • 这是无效的,当我有这样的代码时,它只显示表中的最后一个条目。我不确定为什么它没有得到正确的信息。
  • 在你的映射中包含模态是没有意义的。我宁愿把它作为一个传递当前编辑的道具的单个组件实例拉出来
  • @gaditzkhori 我该怎么做呢?
  • 因为Zohaib @Zohaib exaplined 的方式,基本上最终会加载所有用户并像这样在api中显示最后一个对象。 gyazo.com/e061706c30ab5769c66365f39bb511ba
猜你喜欢
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 2016-10-24
相关资源
最近更新 更多