在父组件

时间:2016-03-09 18:42:36

标签: reactjs

我有一个名为CreateTicket的按钮组件和一个名为IndividualTicketInput的点击我要渲染的组件。我创建了一个父组件,我目前有这两个组件。我需要一个函数,在第一个IndividualTicketInput下面的父组件中点击一个新的票证组件,依此类推。我知道我必须进入门票阵列,但我仍在学习反应并且无法理解这些概念。你最好如何做到这一点,如果你需要明确我的结论,请告诉我。

按钮组件

var CreateTicket = React.createClass({
  getInitialState: function() {
    return{};
  },
  render: function() {
    return(
      <button type="button" className="add-another-ticket">
        +Add Ticket
      </button>
    );
  }
})

Ticket Component **(这是我想点击时渲染的组件)

var IndividualTicketInput = React.createClass({
  getInitialState: function() {
    return { ticket: {name: '', quantity: '', price: null} };
  },
  render: function() {
    return (
      <ul>
        <li>
          <label>Ticket Name</label>
          <input className="ticket-name" type="text" placeholder="E.g. General Admission" value={this.state.ticket.name} />
        </li>
        <li>
          <label>Quantity Available</label>
          <input className="quantity" type="number" placeholder="100" value={this.state.ticket.quantity} />
        </li>
          <li>
            <label>Price</label>
            <input className="price" type="number" placeholder="25.00" value={this.state.ticket.price} />
          </li>
        <li>
          <button type="button" className="delete-ticket" onClick={this.deleteTicket}><i className="fa fa-trash-o delete-ticket"></i></button>
        </li>
      </ul>
    );
  }
});

门票组件

var Tickets = React.createClass({
  getInitialState: function() {
    return {tickets: [] };
  },
  createNewTicket: function() {

    // where the push happens on click to create the new IndividualTicketInput component

    // this is what I am currently trying but it isn't working
    var tickets = this.state.tickets;
     this.state.tickets.push(
      <IndividualTicketInput />
    )
    this.forceUpdate();

  },
  render: function() {
    return (
      <div>
        <IndividualTicketInput />
        // new component will render here
        <div>{this.state.tickets}</div>
        <CreateTicket onClick={this.createNewTicket} />
      </div>
    );
  }
});

1 个答案:

答案 0 :(得分:3)

有这个工作。附加了子按钮组件的道具,然后使用push传递给组件。

按钮组件

var CreateTicket = React.createClass({
  getInitialState: function() {
    return{};
  },
  render: function() {
    return(
      <button type="button" onClick={this.props.createTicket} className="add-another-ticket">
        +Add Ticket
      </button>
    );
  }
})

门票组件:

var Tickets = React.createClass({
  getInitialState: function() {
    return {
      tickets: []
    }
  },
  componentDidMount: function() {
    console.log('this mounted')
  },
  onClick: function() {
    this.state.tickets.push(
      <IndividualTicketInput />
    )
    this.forceUpdate();
  },
  render: function() {
    return (
      <div>
        <IndividualTicketInput />
        {this.state.tickets}
        <CreateTicket createTicket={this.onClick} />
      </div>
    );
  }
});

我遇到的唯一问题是关键情况,但我会弄清楚。谢谢所有人看了这个。