在反应中打开一个弹出窗口

时间:2019-04-04 14:59:34

标签: javascript reactjs bootstrap-4

当我单击react上的按钮时,我想打开一个弹出窗口,我有这个,但是弹出窗口不会出现:

 <button type="button" class="btn btn-primary" data-toggle="modal" data-target={`#${props.idMessage}`}>
                {props.idMessage}
            </button>


            <div class="modal fade" id={props.idMessage} tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

使用react调试工具,我可以看到props.id明显不同于每个对象,并且我的数据目标上的值与我的id相同,如您所见,弹出窗口应该出现:

enter image description here

4 个答案:

答案 0 :(得分:1)

您可以考虑将弹出窗口创建为可重复使用的组件,该组件仅呈现props.message。 假设您在App.js中有按钮,这是在其上添加点击侦听器的方法。

class App extends Component {
  state = {showPopup: false};

  openPopupHandler = () => {
    this.setState({showPopup: true});
  }
  
  closePopupHandler = () => {
    this.setState({showPopup: false});
  }

  
  render() {
    let popup = null;
    if(this.state.showPopup) {
      popup = (<Popup message='the text you need to display' closeMe={this.closePopupHandler}/>);
    } 
    return(
      <div>
      <button onClick={this.clicked}>Click me </button>
      {popup}
      </div>
    );
  }
}

您可以按如下所示定义弹出组件。

Popup.js

const popup = (props) => {
return (
  <div>
    <p>{props.message}</p>
    <button onClick={props.closeMe}>Close Popup</button>
  </div>
);
}

此外,根据需要的大小设置弹出组件的样式,并使其z-index大于父组件的z-index。

答案 1 :(得分:0)

这如何:

class PopUp extends Component {
 constructor(props) {
    super(props);
    this.state = {
        hide: false
    };
 }
 clicked(){
     this.setState({
       hide: true
     });
 }
 render() {
     return (
        <div>
        <button type="button" class="btn btn-primary" data-toggle="modal" onClick={() => this.clicked()} >
            Click Me
        </button>
        {
          this.state.hide? 
              <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">Required PopUp </div>
              : null
        }
        </div>
     );
  }
}
  

您可以在代码中将其用作<PopUp>

答案 2 :(得分:0)

这是使用React Hooks实现这一目标的现代方法

import React, { useState } from "react";

const PopUp = ({ idMessage }) => {
  // create state `open` with default as false
  const [open, setOpen] = useState(false);
  return (
    <>
      {/* click of button toggles `open` value therefore visibility */}
      <button
        onClick={() => setOpen(!open)}
        type="button"
        className="btn btn-primary"
        data-toggle="modal"
        data-target={`#${idMessage}`}
      >
        {idMessage}
      </button>
      {/* If open is true show your <div /> */}
      {open && (
        <div
          className="modal fade"
          id={idMessage}
          tabIndex="-1"
          role="dialog"
          aria-labelledby="exampleModalLabel"
          aria-hidden="true"
        >
          content
        </div>
      )}
    </>
  );
};

export default PopUp;

答案 3 :(得分:-1)

任何人都可以在 REACT 中说, 如何弹出 - 2 个不同的按钮。 通过单击 button1 ,我们必须获得 button1 的 id。 和 button2 一样