0

我有一个带有餐点列表的应用程序,单击餐点应该会在屏幕上显示一个模式,其中包含有关餐点的更多信息。

所以我正在尝试使用react-modal包将基本模式编码为可重用组件。

但是,当我尝试“激活”模式时,它不起作用。该openModal方法确实被触发,但模式没有显示在屏幕上。

应用程序.js:

import React from 'react';

import MealCard from './MealCard';
import MealModal from './MealModal';


export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      modalIsOpen: false
    }
    this.openModal = this.openModal.bind(this);

  };

  openModal() {
    this.setState({modalIsOpen: true});
    console.log(this.state.modalIsOpen);
  }

  render() {
    return (
      <div>
        <div className="app-wrapper" style={{display: 'flex'}}>
          <div className="container">
            <div className="row">
              {[...Array(20)].map((x, i) =>
                  <div className="col-sm-6 col-xs-12 " key={i} onClick={this.openModal}>
                    <MealCard />
                  </div>
                )}
          </div>
        </div>
      </div>
      <MealModal isOpen={this.state.modalIsOpen}/>
    </div>
    );
  }
}

MealModal.js

import React from 'react';
import Modal from 'react-modal';

const customStyles = {
  content : {
    top                   : '50%',
    left                  : '50%',
    right                 : 'auto',
    bottom                : 'auto',
    marginRight           : '-50%',
    transform             : 'translate(-50%, -50%)'
  }
};

Modal.setAppElement('#app')

export default class MealModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalId: 0,
      modalIsOpen: false
    };

    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
  }

  componentWillMount() {
    this.setState({modalId: 3})
  }

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

  closeModal() {
    this.setState({modalIsOpen: false});
  }
  render() {
    return (
      <Modal
        isOpen={this.props.modalIsOpen}
        onRequestClose={this.closeModal}
        style={customStyles}
        contentLabel="Meal Modal"
      >
        <div className="modal-wrapper">
          <div className="container text-center">
            <h1>Hello</h1>
            <h2>ID of this modal is {this.state.modalId}</h2>
            <h3>This is an awesome modal.</h3>
            <button onClick={this.closeModal}>close</button>
          </div>
        </div>
      </Modal>
    )
  }
}
4

1 回答 1

2

您将isOpen作为道具传递并在组件中使用modalIsOpen(props) 。MealModal

如评论中所述,您可以使用isOpen={this.props.isOpen}. 使用两种状态来服务于同一目的是没有意义的,一种modalIsOpenApp组件中,另一种modalIsOpenMealModel组件中

于 2018-07-24T19:55:22.107 回答