Bootstrap 模态反应挂钩

Boostrap Modal React Hook

我正在尝试通过 Bootstrap 模态示例学习 React Hooks。我有以下模态(来自 react bootstrap 网站)。

import React, { useState } from "react";
import {Button, Modal} from 'react-bootstrap';

function SimpleModal() {

const [show, setShow] = useState(false);

const handleClose = () => setShow(false);
const handleShow = () => setShow(true);

return (
  <>
    <Button variant="primary" onClick={handleShow}>
      Launch demo modal
    </Button>

    <Modal show={show} onHide={handleClose} animation={true}>
      <Modal.Header closeButton>
        <Modal.Title>Modal heading</Modal.Title>
      </Modal.Header>
      <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={handleClose}>
          Close
        </Button>
        <Button variant="primary" onClick={handleClose}>
          Save Changes
        </Button>
      </Modal.Footer>
    </Modal>
  </>
);
}
export default SimpleModal;

在 axios 响应中我想显示这个模态

 import React, { Component } from 'react';
 import axios from 'axios';

 import SimpleModal from "../components/SimpleModal"

 export default class CreateInnovation extends Component {


constructor(props) {
    super(props);
    this.onChangeOwnerName = this.onChangeOwnerName.bind(this);
    this.onChangeOwnerDepartment = this.onChangeOwnerDepartment.bind(this);
    this.onChangeOwnerWorkLocation = this.onChangeOwnerWorkLocation.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
        owner_name: '',
        owner_department: '',
        owner_work_location: ''
    }
}

onChangeOwnerName(e) {
    this.setState({
        owner_name: e.target.value
    });
}
onChangeOwnerDepartment(e) {
    this.setState({
        owner_department: e.target.value
    });
}
onChangeOwnerWorkLocation(e) {
    this.setState({
        owner_work_location: e.target.value
    });
}


onSubmit(e) {
    e.preventDefault();
    
    console.log(`Form submitted:`);
    console.log(`Owner Name: ${this.state.owner_name}`);
    console.log(`Owner Department: ${this.state.owner_department}`);
    console.log(`Owner Work Location: ${this.state.owner_work_location}`);

    const newInnovation = {
        owner_name: this.state.owner_name,
        owner_department: this.state.owner_department,
        owner_work_location: this.state.owner_work_location
    };

    axios.post('http://localhost:4000/innov8/create', newInnovation)
        .then(res => {
                if (res.status === 200) {
                    console.log(res.data);
                    <SimpleModal show={"true"} />
                }
            }
         );
    // Purge state
    this.setState({
        owner_name: '',
        owner_department: '',
        owner_work_location: ''
    })
}

render() {
    return (
        <div>
            <h1 id="heading" className='margin'>Innovation<span className="badge badge-primary margin">A3</span></h1>
            <h5 className='margin'>Your Details</h5>

            <form id='Innovationform' onSubmit={this.onSubmit}>
                <div className="container-fluid">
                    <div className="form-row">
                        <div className="col-sm ">
                            <input 
                                id="owner"
                                type="text" 
                                className="form-control" 
                                value={this.state.owner_name}
                                onChange={this.onChangeOwnerName}
                                maxLength="40" 
                                placeholder="Owner Name" 
                                required
                                />
                        </div>
                        <div className="col-sm">
                            <select id="department" className='form-control' value={this.state.owner_department} onChange={this.onChangeOwnerDepartment} required>
                                <option value="" disabled>Select Your Department</option>
                                <option value="acc">Accounts</option>
                                <option value="cat">Catering</option>
                                <option value="com">Commercial</option>
                                <option value="dig">Digitalisation &amp; Business Transformation</option>
                                <option value="dri">Drilling</option>
                                <option value="ele">Electrical</option>
                                <option value="eng">Engineering</option>
                                <option value="fac">Facilities</option>
                                <option value="fin">Finance</option>
                                <option value="hse">HSE</option>
                                <option value="hum">Human Resources</option>
                                <option value="inf">Information Technology</option>
                                <option value="mar">Marine</option> 
                                <option value="mec">Mechanical</option>                
                                <option value="ops">Operations</option>
                                <option value="pay">Payroll</option>                      
                                <option value="pro">Procurement</option>
                                <option value="sub">Subsea</option>
                                <option value="tec">Technical</option>
                                <option value="war">Warehouse</option>   
                                <option value="oth">Other</option>                                  
                            </select>
                        </div>  
                        <div className="col-sm ">
                            <select id="workplace" className='form-control' value={this.state.owner_work_location} onChange={this.onChangeOwnerWorkLocation} required>
                                    <option value="" disabled>Select Your Workplace</option>
                                    <option value="abe">Aberdeen</option>
                                    <option value="car">Stena Carron</option>
                                    <option value="don">Stena Don</option>
                                    <option value="dri">Stena DrillMAX</option>
                                    <option value="for">Stena Forth</option>
                                    <option value="ice">Stena IceMAX</option>
                                    <option value="spe">Stena Spey</option>
                                    <option value="oth">Other</option>
                                </select>
                        </div>
                    </div>                          
                </div>
                <div className="container">
                    <div className="form-row">
                        <div className="col text-center">
                            <button id="formSubmit" type="submit" className="btn btn-primary center-block buttonload">Submit Your Innovation!</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    )
}
 }

我的想法是我需要创建 SimpleModal 组件并使用 setShow 挂钩设置“true”。我一直在寻找几个小时,并且有点挣扎。我刚才在Modal函数中有一个按钮用于测试,但我想删除这个按钮并且只在Axios响应成功时打开模态。我的方向对吗?

这是解决方案 您必须将 show in props 传递给模型

将此状态放入您的 createOwner 组件中,您从中共享了 onSubmit 方法

this.state= {
  show: false,
  owner_name: '',
  owner_department: '',
  owner_work_location: ''
}

传递到您在其中渲染模态的 SimpleModal 组件

在您的创建所有者组件中呈现模式。

<SimpleModal show={this.state.show} onClose={()=>{this.setState({show:false})}} />

在你的 simpleModel 文件中从道具中获取它

import React, { useState } from 'react'
import { Button, Modal } from 'react-bootstrap'
function SimpleModal({ show, onClose }) {
return (
    <>
        <Modal show={show} onHide={onClose} animation={true}>
            <Modal.Header closeButton>
                <Modal.Title>Modal heading</Modal.Title>
            </Modal.Header>
            <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={onClose}>
                    Close
                </Button>
                <Button variant="primary" onClick={onClose}>
                    Save Changes
                </Button>
            </Modal.Footer>
        </Modal>
    </>
)
}
export default SimpleModal

根据您的 post,我假设您实际上不需要那个弹出模式的按钮。相反,您只想根据该 axios 调用来呈现它。如果调用成功(即 returns 200 代码),您希望显示模态。

要做到这一点,实际上我会像您一样使用模态代码创建一个单独的元素,但我会从主 class 控制它的状态。看,你不能从渲染函数之外渲染一些东西,所以在你的 axios 请求函数中你所能做的就是改变一个状态,这将向 class 发出状态已经改变并重新渲染的信号一切顺利。所以我们要做的是在 axios 调用正常时将一个名为 show_modal 的状态变量设置为 true。然后在 render 函数中,渲染 Modal 元素。这里有一个 Sandbox 给你,但我会在这里包含代码以供将来参考:

import React, { useState, Component } from "react";
import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import "bootstrap/dist/css/bootstrap.css";
import axios from "axios";

function SimpleModal({ handleClose }) {
  return (
    <>
      <Modal show={true} onHide={handleClose} animation={true}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

export default class CreateInnovation extends Component {
  constructor(props) {
    super(props);

    this.state = {
      show_modal: false,
      owner_name: "",
      owner_department: "",
      owner_work_location: ""
    };
  }

  makeAxiosCall = () => {
    axios.post("https://httpstat.us/200", { somedata: "" }).then((res) => {
      if (res.status === 200) {
        console.log(res.data);
        this.setState({ show_modal: true });
      }
    });
  };

  handleModalClose = () => this.setState({ show_modal: false });

  render() {
    const { show_modal } = this.state;

    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>

        <button onClick={this.makeAxiosCall}>Make axios call</button>

        {show_modal && <SimpleModal handleClose={this.handleModalClose} />}
      </div>
    );
  }
}

我使用 https://httpstat.us/200 进行测试 axios 调用,因为它总是 returns 200。