簡體   English   中英

React.js:如何在作為props傳入的函數中訪問組件的方法?

[英]React.js: How to access a component's methods within functions that passed in as props?

這是我的代碼,我想在Modal中執行的操作有兩種顯示和隱藏Modal的方法。 並且您可以看到當有人單擊此AddCustomer組件(實際上是一個按鈕)時,將渲染Modal。 我想傳遞兩個自定義函數handleConfirm和handleCancel。 是否可以在handleCancel和handelConfirm中訪問Modal的兩個方法? 或其他好的方法來做這些東西? 謝謝。

var Modal = require('./modal.jsx');

var AddCustomer = React.createClass({
  handleClick: function(){
    $('body').append("<div id='modal-container'></div> ");
    var modal = (
        <Modal
          ref="modal"
          confirm="OK"
          cancel="Cancel"
          onConfirm={this.handleConfirm}
          onCancel={this.handleCancel}
          title="Hello, Bootstrap!">
            This is a React component powered by jQuery and Bootstrap!
        </Modal>
      );

    var modelInstance = React.render(<Modal title="test" />, document.getElementById('modal-container'));
    modelInstance.open();
  },
  handleConfirm:function(){ ??? },
  handleCancel:function(){ ??? },

  render: function() {
    return (
      <div className="ui green button" onClick={this.handleClick}>
        <i className="icon add user"></i>
        Add User
      </div>
    );
  }

});

這是這樣做的方法。 handleConfirmhandleCancel是傳遞給Modal兩個回調, Modal將分別從OK按鈕和cancel Button的onClick處理程序調用

Modal內部應該有類似

<button onClick={this.props.onConfirm}>{this.props.confirm}</button>
<button onClick={this.props.onCancel}>{this.props.cancel}</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM