2015-08-05 4 views
3

http://react-bootstrap.github.io/components.html#modals - Я ищу способ найти событие триггера для 'показанный.bs.modal', а не 'show.bs.modal'.Trigger modal показан для React Bootstrap

Я не вижу никакой документации на некоторые из бутстраповских модальных событий: http://getbootstrap.com/javascript/#modals-events

var NewPerson = React.createClass({ 

    getInitialState: function(){ 
    return { showModal: false }; 
    }, 

    componentDidMount: function() { 
    // removed irrelevant code 
    }, 

    close: function(){ 
    this.setState({ showModal: false }); 
    }, 

    open: function(){ 
    this.setState({ showModal: true }); 
    }, 

    submit: function(e) { 
    // removed irrelevant code 
    }, 
    render: function() { 
    var Button = ReactBootstrap.Button; 
    var ButtonInput = ReactBootstrap.ButtonInput; 
    var Modal = ReactBootstrap.Modal; 

    return (
     <div> 
     <Button 
      className="pull-right bottom-20" 
      bsStyle='success' 
      bsSize='large' 
      onClick={this.open} 
     > 
      Create New Person 
     </Button> 

     <Modal id="new-person-modal" show={this.state.showModal} onHide={this.close}> 
      <Modal.Header closeButton> 
      <Modal.Title>Create a New Person!</Modal.Title> 
      </Modal.Header> 
      <Modal.Body> 
      <form id="new-person-form" onSubmit={this.submit} accept-charset="UTF-8" method="POST" novalidate="novalidate"> 
       <div className="row"> 
       <div className="form-group col-md-12"> 
        <input type="text" className="form-control" id="author" name="author" ref="author" placeholder="Author (First + Last)" required /> 
       </div> 
       </div> 
       <ButtonInput 
       type="submit" 
       value="Submit" 
       bsStyle="success" 
       bsSize="large" 
       onSubmit={this.submit} 
       disabled={this.state.disabled} /> 
      </form> 
      </Modal.Body> 
     </Modal> 
     </div> 
    ); 
    } 
}); 

React.render(<NewPerson url="/person" />, document.getElementById('person-new')); 

Я даже пытался взломать его, просто делая это в JQuery в сторону, которая также не работает ,

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#new-person-modal').on('shown.bs.modal', function (e) { 
    console.log('modal displayed'); 
    // now can execute dynamic JS 
    }); 
}); 
</script> 

Любая идея, как инициировать событие 'on показало'? Я тоже ничего не могу найти в источнике реакции-бутстрапа.

ответ

7

Существует правильный способ: использовать событие onEntered.

<Modal 
    onEntered = { function(){ console.log("Modal is Shown") }} 
> 

Это событие вызывается, когда завершается переход, который показывает модальный.

Есть 6 переход вызывает в общей сложности:

<Modal 
    onExit  = { function(){ console.log("onExit ") }} 
    onExiting = { function(){ console.log("onExiting ") }} 
    onExited = { function(){ console.log("onExited ") }} 

    onEnter = { function(){ console.log("onEnter ") }} 
    onEntering = { function(){ console.log("onEntering") }} 
    onEntered = { function(){ console.log("onEntered ") }} 
> 

Вот что они делают:

onEnter  = Callback fired before the Modal transitions in 

onEntering = Callback fired as the Modal begins to transition in  

onEntered = Callback fired after the Modal finishes transitioning in 


onExit  = Callback fired right before the Modal transitions out 

onExiting = Callback fired as the Modal begins to transition out 

onExited = Callback fired after the Modal finishes transitioning out 

На момент написания, это решение не документированы. Я отправляю запрос на растяжение, поэтому, надеюсь, вскоре они обновят документы.

3

Самый простой способ создать не-визуальный компонент, который будет вызывать переданную функцию визуализации и рендеринга этого компонента где-то внутри Modal.Body:

render: function() { 
    //... 
    <Modal.Body> 
     //... 
     <Notifier onShown={this.onModalShown} /> 
     //... 
    </Modal.Body> 
    //... 
} 

UPDATE: Это как компонент Notifier может должны быть реализованы:

var Notifier = React.createClass({ 
    componentDidMount: function(){ 
     this.props.onShown(); 
    }, 
    render: function() { 
     return null; 
    } 
}); 
+0

Можете ли вы сломать это немного больше? Я не уверен, что понимаю, как этот Notifier будет работать. Кроме того, довольно новый для React/JSX – Du3

+0

Конечно, я обновлю свой первоначальный ответ – const314

+0

Отлично! И чтобы помочь кому-либо еще, кто может это сделать, убедитесь, что вы добавили функцию вModalShown() в Modal. – Du3

0

Я также имел тот же самый вопрос, и это то, что я пытался ...

Class Modal extends React.Component { 

     showModal(){ 
     let obj = this.refs.modal; 
     //write the required code here 
     } 
render() { 
    return (
     <div> 
     <div className="standard-content"> 
       <p><a className="btn" onClick={this.showModal} data-toggle="modal" data-target="#exampleModal">Modal popup</a></p> 
     </div> 
     <div ref="modal" className="modal" id="exampleModal" role="dialog" > 
      <div className="modal-dialog"> 
       <div className="modal-content"> 
       <div className="modal-header">  
        <h4 className="modal-title">Header area</h4> 
       </div> 
       <div className="modal-body"> 
        body goes here..    
       </div> 
       </div> 
      </div> 
      </div> 
     </div> 

    ); 
    } 
} 

Как я использую ES6 поэтому я пошел с классовым подходом. Я создал контейнер div для модального содержимого и дал ссылку ref для ссылки. Затем при щелчке тега я привязывал обработчик, который будет срабатывать при появлении модальности. С помощью this.refs вы можете получить доступ к модальному. Надеюсь, это поможет вам.

Смежные вопросы