How to open/close react-bootstrap modal programmatically?

后端 未结 4 451
心在旅途
心在旅途 2020-12-14 07:30

I need to open/close modal like

$(element).modal(\'show\')

How to do that?

4条回答
  •  误落风尘
    2020-12-14 07:52

    What you are looking for is the custom modal trigger, which uses the OverlayMixin and allows you to manage the modal's state yourself. You can control whether the modal is shown using this.setState({isModalOpen: true}) to achieve the equivalent of what you asked for in your post in the example below. The following code is from the react-bootstrap website (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 (
          
        );
      },
    
      // 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 ;
        }
    
        return (
          
            
    This modal is controlled by our custom trigger component.
    ); } }); React.render(, mountNode);

    UPDATE (Aug 4, 2015)

    In the newest version of React-Bootstrap, whether a modal is shown or not is controlled by a show prop which is passed to the modal. The OverlayMixin is no longer needed to control the modal state. Controlling the state of the modal is still done via setState, in this example via this.setState({ showModal: true }). The following is based off the example on the React-Bootstrap website:

    const ControlledModalExample = React.createClass({
    
      getInitialState(){
        return { showModal: false };
      },
    
      close(){
        this.setState({ showModal: false });
      },
    
      open(){
        this.setState({ showModal: true });
      },
    
      render() {
        return (
          
    Modal heading
    Modal content here
    ); } });

提交回复
热议问题