React Component按钮以触发另一个组件中的模态(使用react-bootstrap)

时间:2018-11-12 08:10:21

标签: event-handling

我有一个productCard,其中按下了addToCart按钮,有一次发生后会弹出shoppingCart模式,而App组件则将其全部呈现。我很难传递来自addToCart按钮(在productCard Comp中)的click事件以触发(shoppingCart comp)中的handleShow()方法。这是我的代码:

shoppingCart.js:

import React from "react";
import {
  Popover,
  Tooltip,
  Button,
  Modal,
  OverlayTrigger
} from "react-bootstrap";
// import { ProductCard } from "./productCard.js";
import "./shoppingCart";

export class ShoppingCart extends React.Component {
  constructor(props) {
    super(props);

    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);

    this.state = {
      show: false
    };
  }

  handleClose() {
    this.setState({ show: false });
  }

  //I'm trying to trigger this method from the onClick event in 
  //productCard.js

  handleShow() {
    this.setState({ show: true });
  }

  render() {
    return (
      <div>

        <Modal show={this.state.show} onHide={this.handleClose}>
          <Modal.Header closeButton>
            <Modal.Title>Your Cart</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <p>Current Items: </p>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.handleClose}>Continue Shopping</Button>
            <Button>Checkout</Button>
          </Modal.Footer>
        </Modal>
      </div>
    );
  }

}

productCard.js

import React from "react";
import { Grid, Row, Col, Thumbnail, Button } from "react-bootstrap";
import { ShoppingCart } from "./shoppingCart.js";
import "./productCard.css";

export class ProductCard extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className="ProductCard">
        <Grid className="Grid">
          <Row>
            <Col xs={12} sm={6} md={3}>
              <Thumbnail
                className="Thumbnail"
                src="http://placehold.jp/300x200.png"
                alt="300x200"
              >
                <h3>Product Name</h3>
                <p>Description</p>
                <p>
                  <Button bsStyle="primary">Read More</Button>
                  &nbsp;
                  <Button bsStyle="success" onClick={this.props.handleShow}>Add to Cart</Button>
                </p>
              </Thumbnail>
            </Col>
          </Row>
        </Grid>
      </div>
    );
  }
}

我敢肯定这是一个简单的误会,但我对此一无所知,这使我受够了很长时间。感谢您的帮助!

0 个答案:

没有答案