简体   繁体   English

单击按钮后,模态主体无法在html中呈现组件

[英]The Modal body not render the component in html after button click

I am new to react. 我是新来的反应。 I try to use the button onClick to call function for render the component in html. 我尝试使用按钮onClick调用函数以在html中呈现组件。

After execution, does not appear on the page. 执行后,不会出现在页面上。 Like this: https://imgur.com/a/jnPwEGN 像这样: https : //imgur.com/a/jnPwEGN

But when I check the html element (F12), the react-c3js element is contains the element, and then it suddenly appears in the screen, like this: https://imgur.com/a/qHbv1zq 但是当我检查html元素(F12)时,react-c3js元素包含了该元素,然后它突然出现在屏幕上,如下所示: https ://imgur.com/a/qHbv1zq

But if I don't look at it and wait, the chart will never appear. 但是,如果我不看它并等待,该图表将永远不会出现。

This is my .js file 这是我的.js文件

// draw the Chart in html
function drawHistoryChart(data) {
    console.log("data: ", data);
    const data2 = {
        columns: [
            ['data1', 30, 200, 100, 400, 150, 250],
            ['data2', 50, 20, 10, 40, 15, 25]
        ]
    };
    ReactDOM.render(<C3Chart data={data2} />, document.getElementById('react-c3js'));
}

//
class CarPark extends React.Component {
    static defaultProps = {
        parkId: "Not Found Id",
        parkName: "Not Found Name",
        address: "Not Found Address",
        totalSpace: 0,
        surplusSpace: 0,
        payGuide: "Not Found Pay Guide",
    };
    static propTypes = {
        parkId: PropTypes.string.isRequired,
        parkName: PropTypes.string.isRequired,
        address: PropTypes.string.isRequired,
        totalSpace: PropTypes.number.isRequired,
        surplusSpace: PropTypes.string.isRequired,
        payGuide: PropTypes.string.isRequired,
    };

    // Fetch data and pass data to drawHistoryChart Function
    requestHistoryOfCarPark(parkId, week, time) {
        fetch("/findHistoryByCarPark?place=" + parkId + "&week=" + week + "&time=" + time)
            .then((response) => {
                return response.json();
            }).then((jsonData) => {
                drawHistoryChart(jsonData);
            }).catch((err) => {
                console.log('error: ', err);
            });
    }

    render() {
        return (
            <div className="card">
                <div className="card-header">
                    <button className="btn" data-toggle="modal" data-target="#myModal" onClick={() => this.requestHistoryOfCarPark(this.props.parkId, getWeek(), getTime())}><i className='fas fa-search' style={style}></i></button>
                    {this.props.parkId}-{this.props.parkName}
                </div>
                <div className="card-body">
                    <div>地址:{this.props.address}</div>
                    <div>總車位:{this.props.totalSpace}</div>
                    <div>剩餘車位:{this.props.surplusSpace}</div>
                    <div>價錢資訊:{this.props.payGuide}</div>
                </div>
            </div >
        )
    }
}

and this is my html 这是我的HTML

<div class="modal fade" id="myModal">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Modal Heading</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <div class="modal-body">
          <div id="react-c3js"></div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

Has anyone encountered this problem? 有没有人遇到这个问题? Very grateful for any help! 非常感谢您的帮助!

Problem 问题

Your code isn't working because you are not handling the Javascript for the toggling of the Modal correctly. 您的代码无法正常运行,因为您没有正确处理Java代码以正确切换Modal。 React is a Javascript library, if you are using it take full advantage of it. React是一个Javascript库,如果您正在使用它,请充分利用它。

You do not need to pass data-toggle attributes in your HTML. 您无需在HTML中传递data-toggle属性。 You don't want to use straight up HTML like that if you are using React. 如果您正在使用React,则不希望使用像HTML这样的直接HTML。 You want to create a Modal functional component and use JSX. 您想要创建一个Modal功能组件并使用JSX。 Convert your modal HTML into a React functional component that accepts isOpen and has a onClose method. 将您的modal HTML转换为一个接受isOpen并具有onClose方法的React功能组件。

Solution

There isn't a one size fits all solution to your issue here. 这里没有一种适合您问题的解决方案。 You can approach this in a couple ways. 您可以通过几种方法来解决这个问题。 You could create a Modal component on tap on the shoulders of a library to do the heavy lifting for you. 您可以在库的肩膀上点击创建一个Modal组件,以完成繁重的工作。 I strongly recommend the latter since you are new. 强烈建议您使用后者,因为您是新手。 Then play around with building your own component yourself. 然后自己动手构建自己的组件。

Two libraries that are popular with React are Material UI or Reactstrap . React最受欢迎的两个库是Material UIReactstrap

You can read up on Material UI here: https://material-ui.com/ . 您可以在此处在Material UI上阅读: https : //material-ui.com/ And Reactstrap here: https://reactstrap.github.io/ 和Reactstrap在这里: https ://reactstrap.github.io/

These libraries have a ton of Bootstrap goodies that you can play around with in your application. 这些库具有大量的Bootstrap好东西,您可以在应用程序中使用它们。

Here's an example of how you could use Reactstrap in you component to get started. 这是一个如何在组件中使用Reactstrap的示例。

Reactstrap: Modals Reactstrap:模态

Add Reactstrap to your project. Reactstrap添加到您的项目中。 Using npm: npm i reactstrap react-dom or using yarn: yarn add reactstrap react-dom . 使用npm: npm i reactstrap react-dom或使用yarn: yarn add reactstrap react-dom I assume you have bootstrap installed as well since you are using the bootstrap classes. 由于您正在使用bootstrap类,因此我假设您也安装了bootstrap。 You should be good to go to start using reactstrap at this point. 此时,您应该可以开始使用reactstrap了。

Updating CarPark Component 更新停车场组件

import React, { Component, useState } from 'react';
import { Button, Card, CardHeader, CardBody, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

class CarPark extends Component {
   const [isOpen, setIsOpen] = useState(false) //creating a state variable isOpen whose default value is false

  //fetch your data method

   //function for toggling the modal, accepts no params
   //ES6 notation, the arrow function
   const toggleModal = () => {
     setIsOpen(!isOpen); //setting state equivalent to this.setState({ isOpen: !this.state.isOpen })
   }; 

   //function for opening the modal and calling requestHistoryOfCarPark
   const handleOpenModal = () => {
     const { parkId } = this.props; //destructuring props so you don't have to right this.props.parkId everywhere you can just call parkId
     this.requestHistoryOfCarPark(parkId, getWeek(), getTime());
     setIsOpen(true); //whenever the button is clicked always open the modal
   }; 

   render() {
     const { address, parkId, parkName, payGuide, surplusSpace, totalSpace } = this.props //destructuring props again

     return(
      //this <> empty tag is a Fragment
      <>
       <Card>
        <CardHeader>
          <Button onClick={handleOpenModal}><i className='fas fa-search' style={style}></i></Button>
          { parkId } - { parkName }
        </CardHeader>
        <CardBody>
          <div>{ address } </div>
          <div> { totalSpace } </div>
          <div> { surplusSpace } </div>
          <div> { payGuide } </div>
        </CardBody>
       </Card>
       //Put your modal under the component where you want to access it
       <Modal isOpen={isOpen} toggle={toggleModal}>
        <ModalHeader tag='h4'> Modal Heading </ModalHeader>
        <ModalBody><div id="react-c3js"></div></ModalBody>
        <ModalFooter>
          <Button color='secondary' onClick={toggleModal}>Close</Button>
        </ModalFooter>
       </Modal>
     </> 
    )
}

} }

Fragments I wrapped the Card and Modal inside of a Fragment you could just as easily use a <div></div> but fragments allow you to have sibling components without needing to wrap in an HTML parent ie <div> . 片段我将CardModal包裹在一个Fragment中,您可以很容易地使用<div></div>但是片段允许您具有同级组件,而无需包装HTML父级,即<div> You can read up on Fragments here . 您可以在此处阅读Fragments。

Suggestion 建议

I know getting into a new framework is exciting and you just want to dive right in, but I highly recommend reading through the React documentation (which can be daunting) and doing some tutorials or reading walkthrough guides. 我知道进入一个新框架是令人兴奋的,并且您只是想深入学习,但是我强烈建议您阅读React文档 (这可能会令人生畏),并做一些教程或阅读演练指南。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM