解决方法
您正在寻找的是自定义模态触发器,它使用OverlayMixin,并允许您自己管理模态的状态。您可以使用this.setState({isModalOpen:true})来控制是否显示模态,以实现与下面示例中您在帖子中所要求的相同。以下代码来自react-bootstrap网站(
http://react-bootstrap.github.io/components.html#modals):
const CustomModalTrigger = React.createClass({ mixins: [OverlayMixin],getInitialState() { return { isModalOpen: false }; },handleToggle() { this.setState({ isModalOpen: !this.state.isModalOpen }); },render() { return ( <Button onClick={this.handleToggle} bsStyle='primary'>Launch</Button> ); },// This is called by the `OverlayMixin` when this component // is mounted or updated and the return value is appended to the body. renderOverlay() { if (!this.state.isModalOpen) { return <span/>; } return ( <Modal bsStyle='primary' title='Modal heading' onRequestHide={this.handleToggle}> <div className='modal-body'> This modal is controlled by our custom trigger component. </div> <div className='modal-footer'> <Button onClick={this.handleToggle}>Close</Button> </div> </Modal> ); } }); React.render(<CustomModalTrigger />,mountNode);
更新(2015年8月4日)
在React-Bootstrap的最新版本中,无论是否显示模态是由传递给模态的show prop控制的。 OverlayMixin不再需要控制模式状态。控制模态的状态仍然通过setState完成,在本例中通过this.setState({showModal:true}))。以下是基于React-Bootstrap网站上的示例:
const ControlledModalExample = React.createClass({ getInitialState(){ return { showModal: false }; },close(){ this.setState({ showModal: false }); },open(){ this.setState({ showModal: true }); },render() { return ( <div> <Button onClick={this.open}> Launch modal </Button> <Modal show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>Modal heading</Modal.Title> </Modal.Header> <Modal.Body> <div>Modal content here </div> </Modal.Body> <Modal.Footer> <Button onClick={this.close}>Close</Button> </Modal.Footer> </Modal> </div> ); } });