我正在使用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并改变模态的状态来完成。我到底错在了什么?
谢谢!
答案 0 :(得分:4)
您可以在父母
中尝试以下代码吗?<button onClick={() => this._modal.openModal()}>click</button>
当您使用ref属性调用模态组件时,可以像上面的代码一样调用。
<Modal ref={(modal) => { this._modal = modal; }} />
答案 1 :(得分:2)
简单的方法,通过道具来实现:
modal.js
var MostCommonDictionaryValuesFirst = PersonalCraft_SubOffset1_FunctionAddress.GroupBy(_ => _.Value).OrderByDescending(_ => _.Count()).SelectMany(_ => _);
已导入模态的组件中。
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
}}
>