简体   繁体   English

盖茨比在按钮单击时打开模态窗口

[英]Gatsby open modal window on button click

I'm working on a website about donation using Gatsby v2 (Reactjs) and I need an example like open modal window on button donation click using Gatsby or ReactJS.我正在一个关于使用 Gatsby v2 (Reactjs) 进行捐赠的网站上工作,我需要一个示例,例如使用 Gatsby 或 ReactJS 单击按钮捐赠时的打开模式窗口。 I search on internet and I got nothing.我在互联网上搜索,但一无所获。

Thanks in advance.提前致谢。

Here's a simple (Gatsby) page that makes use of react-modal as an example.这是一个简单的 (Gatsby) 页面,它以react-modal为例。 In this example I've replaced the default IndexPage in the Gatsby v2's new starter site that you can generate via the CLI.在本示例中,我替换了 Gatsby v2 的新入门站点中的默认 IndexPage,您可以通过 CLI 生成该站点。

import React, { Component } from 'react'
import ReactModal from 'react-modal'
import { Link } from 'gatsby'

import Layout from '../components/layout'

ReactModal.setAppElement('#main')

class IndexPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isModalOpen: false,
    }
  }
  handleModalOpen = event => {
    // console.log('handleModalOpen: ', event);
    this.setState({ isModalOpen: true })
  }

  handleModalClose = event => {
    // console.log('handleModalOpen: ', event);
    this.setState({ isModalOpen: false })
  }

  render() {
    return (
      <Layout>
        <div id="main">
          <h1>Hi people</h1>
          <p>Welcome to your new Gatsby site.</p>
          <p>Now go build something great.</p>

          <Link to="#" onClick={this.handleModalOpen}>
            Donate Now
          </Link>
        </div>
        <ReactModal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.handleModalClose}
          contentLabel="Example Modal In Gatsby"
        >
          <h2>Donate</h2>
          <button onClick={this.handleModalClose}>Close Modal</button>
        </ReactModal>
      </Layout>
    )
  }
}

export default IndexPage

That should get you going.那应该能让你继续前进。 Best to read up on how to expand on this example using react-modal here (or use an alternative).最好在这里阅读如何使用 react-modal扩展此示例(或使用替代方法)。

First of all the above example will not work because #main doesn't exist, right now the id for Gatsby app is ___gatsby , so it shoul look like this首先,上面的例子将不起作用,因为#main不存在,现在 Gatsby 应用程序的 id 是___gatsby ,所以它应该看起来像这样

ReactModal.setAppElement('#___gatsby')

But it's not good to hope that this id is not going to change in the future.但是希望这个id以后不会变也不好。 So it's better to implement your own React modal component, here is a good example https://www.digitalocean.com/community/tutorials/react-modal-component所以最好实现自己的 React modal 组件,这里有一个很好的例子https://www.digitalocean.com/community/tutorials/react-modal-component

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

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