首页 > 解决方案 > 如何在每次调用 react.js 类方法时将参数传递给其中包含的模式?

问题描述

我有两节课。在 的render()方法中Timeslots,当我将参数传递给this.colhour并在 的实例中使用它时TsModalmodalid总是分配为'11:00-11:30'。如何分配modalid为函数调用中传递的唯一参数?

class Timeslots extends Component {
  popoverHoverFocus() {
    return (
      <Popover id="popover-trigger-hover-focus" title="Table status">
        <strong>P1 -> </strong> <br />
        <strong>P2 -> </strong> <br />
        <strong>S1 -> </strong> <br />
        <strong>S2 -> </strong> <br />
        <strong>S3 -> </strong> <br />
      </Popover>
    );
  }

  colhour(time) {
    return (
      <Col className='halfhour' xs={4} md={1}>
        <TsModal modalid = {time} show={this.state.show} onhide={this.handleClose} onclick={this.handleClose} />
        <OverlayTrigger overlay={this.popoverHoverFocus()}>
          <Button bsStyle="primary" bsSize="small" onClick={this.handleShow}>
            {time} 
          </Button>
        </OverlayTrigger>
      </Col>
    );
  }

  render() {
    return (
      <Grid>
        <br></br>
        <Row className="timeslot">
          {this.colhour('10:00-10:30')}
          {this.colhour('10:30-11:00')}
          {this.colhour('11:00-11:30')}
        </Row>
      </Grid>
    );
  }
}
class TsModal extends React.Component {
  render() {
    return (
      <Modal show={this.props.show} onHide={this.props.onhide}>
        <Modal.Header closeButton>
          <Modal.Title>Book Tables</Modal.Title>
        </Modal.Header>
        <Modal.Body>            
          <hr />
          <Button bsStyle="primary" bsSize="small" href={'http://localhost:4000/?id=' + this.props.modalid}>Pool table 1</Button>
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.props.onclick}>Close</Button>
        </Modal.Footer>
      </Modal>
    );
  }
}

标签: reactjs

解决方案


好吧,我找到了一种将单击的按钮的值传递给TsModal实例的方法。我做了一个处理函数handleButPush并传递keeptime给它。然后我将该值存储在一个状态中buttonPush,并将该状态值传递给 TsModal 实例。由此,每次modalid都被赋予不同的值。keeptime

this.state = {
  show: false, 
  buttonPush: 'invalid',
  list : [],  
  popoverlist : [{status: "Available"},{status: "Available"},{status:"Available"},{status: "Available"},{status:"Available"}]
};

handleButPush(val) {
this.setState({ buttonpush: val });
}

colhour(keeptime,butdisable) {
return(  
    <Col className='halfhour' xs={4} md={1}>
      <TsModal modalid = {this.state.buttonpush} show={this.state.show} onhide={this.handleClose} onclick={this.handleClose} />
        <OverlayTrigger overlay = {() => {this.popoverHoverFocus({keeptime},{butdisable})} } >
          <Button bsStyle="primary" bsSize="small"  onClick={() => { this.handleShow(); this.handleButPush({keeptime}); }}>
            {keeptime} 
          </Button>
        </OverlayTrigger>
    </Col>
);
}

推荐阅读