想要使用HTML5在JavaScript中打开自定义弹出窗口

时间:2016-01-16 07:37:44

标签: html5 react-jsx

我试过这个链接:

http://codepen.io/anon/pen/zxLdgz

http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/

但它没有工作:

我在jsx文件中试过这段代码

<a href="#openModal">Open Modal</a>

<div id="openModal" className="modalDialog">
    <div>
        <a href="#close" title="Close" className="close">X</a>
        <h2>Modal Box</h2>
        <p>This is a sample modal box that can be created using the powers of CSS3.</p>
        <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
    </div>
</div>

此代码:

ondialog() 
{
    <dialog id="window">
        <h3>Sample Dialog!</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum, inventore!</p>
        <button id="exit">Close Dialog</button>
    </dialog>
}
按钮上的

仍然没有用

2 个答案:

答案 0 :(得分:5)

这里实际上没有打开模态的代码,但你可以使用ES6类语法和类属性做这样的事情(你可能需要为此配置正确的babel配置)

import React, { Component } from 'react'

class Page extends Component {

  constructor (props) {
    super(props)
    this.state = { modalActive: false }
  }

  openModal = () => {
    this.setState({ modalActive: true })
  }

  closeModal = () => {
    this.setState({ modalActive: false })
  }

  render () {
    return (
      <div>
        <button onClick={this.openModal}>Open modal</button>

        {this.state.modalActive && (
          <div className='modalDialog'>
            <a title='Close' onClick={this.closeModal}>X</a>
            <h2>Modal</h2>
            <p>This is a sample modal</p>
          </div>
        )}
      </div>
    )
  }
}

我基本上做的是在我的状态中保持一个布尔值来定义是否显示模态,如果值为trulthy,this.state.modalActive上的条件将呈现模态。

答案 1 :(得分:0)

在对话框中添加open属性会使其可见:

render () {
  return (
  <div>
    {this.state.modalActive && (
      <dialog className='modalDialog' open>
      </dialog>
    )}
  </div>
)

}