2017-10-14 59 views
0

我使用的基本組成模式成分反應 - https://github.com/reactjs/react-modal從另一個組件開放模式單擊JS反應

我想實現的是,我想從有進口的模態另一位家長開模。

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和改變模態的狀態。我在這裏做錯了什麼?

謝謝!

回答

2

你可以試試下面的代碼在父母

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

,當你打電話給你的模態分量使用ref屬性,那麼可以調用像上面的代碼。

<Modal ref={(modal) => { this._modal = modal; }} /> 
相關問題