How do I create a popup window in react.js when the button and function are in separate file?

南楼画角 提交于 2021-01-24 09:10:41

问题


Problem Description: There is a button on a webpage, and when I click the button, there will be a popup containing an image. The button is in the file called "index.jsx", and clicking on the button will trigger a function in the file "popUp.js", which will pop a window up. So in essence, the button and the PopUp function are in separate files.

I want to write the function as:

export function PopUp (image: Image){
  return{
    ...
  };
}

which will have the same effect as https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal, except that the content of popup is an image rather than texts. I guess the emphasis of solution is on translating CSS on this webpage to react.js, but not sure how the syntax should look like.

Any idea on how I can implement this?


回答1:


You can do it easily with react-modal. Here is an example, as a bonus I added closing modal when clicking on opened image. Image src and its description should be passed to popUp component as props in data object.

PopUp.js:

import React from 'react';
import Modal from 'react-modal';
import ModalButton from './modal-button';
import style from './style.css';

class PopUp extends React.Component {
  constructor() {
    super();

    this.state = { modalOpened: false };
    this.toggleModal = this.toggleModal.bind(this);
  }

  toggleModal() {
    this.setState(prevState => ({ modalOpened: !prevState.modalOpened }));
  }

  render() {
    const { data } = this.props;
    return (
      <div className={style.modalWrapper}>
        <ModalButton handleClick={this.toggleModal}>
          click to open modal
        </ModalButton>
        <Modal
          className={{ base: [style.base]}}
          overlayClassName={{ base: [style.overlayBase] }}
          isOpen={this.state.modalOpened}
          onRequestClose={this.toggleModal}
          contentLabel="Modal with image"
        >
          <img
            onClick={this.toggleModal}
            src={data.src}
            alt='image displayed in modal'
          />
          <span className={style.text}>{data.description}</span>
        </Modal>
      </div>
    );
  }
}

export default PopUp;

And separated button, as you requested:

import React from 'react';
import style from './style.css';

const ModalButton = props => (
  <button className={style.button} onClick={props.handleClick}>
    {props.children}
  </button>);

export default ModalButton;


来源:https://stackoverflow.com/questions/44712076/how-do-i-create-a-popup-window-in-react-js-when-the-button-and-function-are-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!