模态窗口从未激活

时间:2018-03-07 13:44:24

标签: javascript reactjs dialog modal-dialog user-input

我正在使用javascript React(我是新手)。 从我的主页面,我想点击一个按钮打开一个对话框窗口,允许用户输入一些值。

我发现了模态窗口,所以我在分析了一些例子之后尝试生成一个,但是现在没有任何事情发生......

我试过这段代码:

我的主页,Environment.js:

import React, { Component } from 'react'
import { ReactLoader } from 'Loader'
import Modal from './Modal';

class EnvironmentExtension extends ModelExtension {

constructor (viewer, options) {

 super (viewer, options)
 this.state = { isModalOpen: false };

 this.openModal = this.openModal.bind(this)
 this.closeModal = this.closeModal.bind(this)
 this.react = options.react }

openModal = () => {
 this.react.setState({isModalOpen: true});
 console.log("openModal()");
 console.log('state modal');
 console.log(this.state.isModalOpen)}

closeModal = () => {
 this.react.setState({isModalOpen: false});
 console.log("closeModal()");
 console.log('state modal');
 console.log(this.state.isModalOpen)
}

render () {
 return (
  <button onClick={() => this.openModal()}  
    title="Show map dialog :O">
    <span className="fa fa-hand-o-left"/>
  </button>

  <Modal isOpen={this.state.isModalOpen} onClose={()=>this.closeModal()}>
    content for modal
    <button onClick={()=> this.closeModal()}>
     Close
    </button>
   </Modal> )}

对于模态文件,modal.js:

import React from 'react';
import PropTypes from 'prop-types';

class Modal extends React.Component {
 render() {

 if(!this.props.isOpen) {
  return null;
}

 // The gray background
 const backdropStyle = {
   position: 'fixed',
   top: 0,
   bottom: 0,
   left: 0,
   right: 0,
   backgroundColor: 'rgba(0,0,0,0.3)',
   padding: 50};

 // The modal "window"
 const modalStyle = {
   backgroundColor: '#fff',
   borderRadius: 5,
   maxWidth: 500,
   minHeight: 300,
   margin: '0 auto',
   padding: 30};

return (
  <div className="backdrop">
    <div className="modal">
      {this.props.children}

      <div className="footer">
        <button onClick={this.props.onClose}>
          Close
        </button>
      </div>
    </div>
  </div>
);
}
}

Modal.propTypes = {
  onClose: PropTypes.func.isRequired,
  onOpen: PropTypes.bool,
  children: PropTypes.node
};

export default Modal;

当我运行代码时,我收到此错误:

  

警告:标记上的未知道具isOpenonClose。从元素中删除这些道具

当我点击应该打开对话框的按钮时,我有文本&#34;内容为模态&#34;显示在页面中间,以及按钮取消。 而且,在控制台中,布尔值isModalOpen总是为false ... 根本没有显示对话框...

1 个答案:

答案 0 :(得分:0)

两件事。

首先,我不确定你的警告来自哪里,但请看一下:https://reactjs.org/warnings/unknown-prop.html。也许你有一个没有大写的用户定义组件(你可能在你发布的代码中遗漏了这些组件)。

其次,听起来你的模态正确地打开和关闭,并且你实际上遇到了CSS问题。在modalStyle上添加以下内容:

position:absolute
top:50%;
left:50%;
transform:translate(-50%, -50%);
width:400px;
height:300px;

这应该给你一个起点。

在相关说明中尝试使用UI工具包,如Semantic(https://react.semantic-ui.com),了解React组件的样式。