Bootstrap modal in React.js

前端 未结 12 1396
别跟我提以往
别跟我提以往 2020-12-02 07:19

I need to open a Bootstrap Modal from clicking on a button in a Bootstrap navbar and other places (to show data for a component instance, ie. providing \"editing\" f

12条回答
  •  醉酒成梦
    2020-12-02 07:59

    I was recently looking for a nice solution to this without adding React-Bootstrap to my project (as Bootstrap 4 is about to be released).

    This is my solution: https://jsfiddle.net/16j1se1q/1/

    let Modal = React.createClass({
        componentDidMount(){
            $(this.getDOMNode()).modal('show');
            $(this.getDOMNode()).on('hidden.bs.modal', this.props.handleHideModal);
        },
        render(){
            return (
              

    Modal title

    One fine body…

    ) }, propTypes:{ handleHideModal: React.PropTypes.func.isRequired } }); let App = React.createClass({ getInitialState(){ return {view: {showModal: false}} }, handleHideModal(){ this.setState({view: {showModal: false}}) }, handleShowModal(){ this.setState({view: {showModal: true}}) }, render(){ return(
    {this.state.view.showModal ? : null}
    ); } }); React.render( , document.getElementById('container') );

    The main idea is to only render the Modal component into the React DOM when it is to be shown (in the App components render function). I keep some 'view' state that indicates whether the Modal is currently shown or not.

    The 'componentDidMount' and 'componentWillUnmount' callbacks either hide or show the modal (once it is rendered into the React DOM) via Bootstrap javascript functions.

    I think this solution nicely follows the React ethos but suggestions are welcome!

提交回复
热议问题