【问题标题】:Error on calling react-modal in rails 4 app在 Rails 4 应用程序中调用 react-modal 时出错
【发布时间】:2017-05-01 12:36:39
【问题描述】:

我在带有 react-rails 前端的 rails 4 应用程序中使用 react-modal 时遇到问题。我已经按照这个 SO 问题 How to call react-modal from rails-assets.org in react-rails component 和这个 GitHub 问题 https://github.com/reactjs/react-rails/issues/510 中的步骤进行操作,但它们似乎都不起作用。

这是我的 Gemfile 中的 rails-assets gem

source 'https://rails-assets.org' do
  gem 'rails-assets-react-modal'
end

这是我的 application.js 文件

//= require react
//= require ./vendor/react-modal-v1.6.4
//= require react_ujs
//= require react-modal

//= require ./vendor/react-modal-v1.6.4 调用是对 react-modal 的编译文件的调用。我是按照上面 github 问题链接中提供的说明进行的。

最后,这是我的组件定义

var ModalTest = React.createClass({
  getInitialState: function() {
    return {
      modalIsOpen: false
    }
  },

  openModal: function() {
    this.setState({modalIsOpen: true});
  },

  closeModal: function() {
    this.setState({modalIsOpen: false});  
  },

  render: function() {
    return (
      <div>
        <button className="btn btn-primary" onClick={this.openModal}>
          Open Modal
        </button>
        <ReactModal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal}
          contentLabel="Modal"
        >
          <h1>Test Modal</h1>
        </ReactModal>
      </div>
    );
  }
});

我在控制台上收到以下错误:

未捕获的错误:react-modal:您必须使用 Modal.setAppElement(el) 设置一个元素才能使其可访问

我错过了什么? 提前谢谢各位。

【问题讨论】:

  • 什么是react-modal?是你设置的文件名吗?

标签: ruby-on-rails reactjs react-rails react-modal


【解决方案1】:

我在this GitHub issue for react-modal 中发帖的yachaka 找到了答案。

脚本在 DOM 之前加载,导致 react-modal 在其存在之前将 modal 的父元素设置为 document.body

这可以通过添加生命周期方法componentWillMount来解决,如下:

componentWillMount: function() {
  ReactModal.setAppElement('body');
}

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 2018-02-05
    • 2015-03-17
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多