2

我正在使用 react 的基本组件模态组件 - https://github.com/reactjs/react-modal

我想要实现的是我想从另一个导入了模态的父级打开模态。

Parent.js
<button onClick={() => this.refs.setState({modalIsOpen: true})}> - THIS BUTTON ELEMENT IS IN ANOTHER COMPONENT

Modal.js
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';

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

class App extends React.Component {
 constructor() {
 super();

 this.state = {
  modalIsOpen: false
 };

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

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

afterOpenModal() {
 // references are now sync'd and can be accessed.
 this.subtitle.style.color = '#f00';
 }

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

render() {
 return (
  <div>
    <button onClick={this.openModal}>Open Modal</button>
    <Modal
      isOpen={this.state.modalIsOpen}
      onAfterOpen={this.afterOpenModal}
      onRequestClose={this.closeModal}
      style={customStyles}
      contentLabel="Example Modal"
    >

      <h2 ref={subtitle => this.subtitle = subtitle}>Hello</h2>
      <button onClick={this.closeModal}>close</button>
      <div>I am a modal</div>
      <form>
        <input />
        <button>tab navigation</button>
        <button>stays</button>
        <button>inside</button>
        <button>the modal</button>
      </form>
    </Modal>
  </div>
);
}
}

export default App

我已经读过这可以使用 refs 并更改模态的状态来完成。我在这里到底做错了什么?

谢谢!

4

2 回答 2

5

您可以在父项中尝试以下代码吗

<button onClick={() => this._modal.openModal()}>click</button>

当您调用模态组件时,请使用ref属性,然后可以像上面的代码一样调用。

<Modal ref={(modal) => { this._modal = modal; }} />
于 2017-10-15T00:05:30.513 回答
2

简单的方法,通过道具做到这一点:

modal.js

                import ....

                <Modal
                aria-labelledby="simple-modal-title"
                aria-describedby="simple-modal-description"
                className={classes.modal}
                open={this.props.handleOpen}
                onClose={this.props.handleClose}
                BackdropComponent={Backdrop}
                BackdropProps={{
                    timeout: 1000
                }}
            >

在您的组件中导入了模态。

///some code here
state = {
        isOpen: Boolean(false)
    };
                <externalElement onClick={() => this.setState({ isOpen: true })}>title ... </externalElement>
                  <importedModal
                            handleOpen={this.state.isOpen}
                            handleClose={() => this.setState({ isOpen: false })}
                        />
于 2020-02-10T09:34:57.793 回答