首页 > 解决方案 > React JS:如何将数据从一个组件发送到另一个组件的 onClick 事件

问题描述

我正在设计一个自行车租赁应用程序。主区域页面在卡片中显示可用的自行车以及自行车的名称、型号和图像。现在,当我们单击图书时,我们将被重定向到结帐页面。我需要将所选自行车的名称和型号信息发送到结帐页面。怎么做?

BikesCard.js

import React, { Component } from 'react';
import {
  Card, CardImg, CardText, CardBody,
  CardTitle, CardSubtitle, Button
} from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

class BikesCard extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log(this.props.bikes)
    this.props.propdata.history.push(`/Checkout`)
  }

  render() {
    return (
      <div>
        <Card className="Card">
          <CardImg top width="100%" src={this.props.bikes.image} alt="Card image cap" />
          <CardBody>
            <CardTitle>{this.props.bikes.name}</CardTitle>
            <CardSubtitle>{this.props.bikes.model}</CardSubtitle>
            <CardText>{this.props.bikes.description}</CardText>
            <Button onClick={this.handleClick}>Book</Button>
          </CardBody>
        </Card>
      </div>
    )
  }

}

export default BikesCard;

结帐.js

import React, { Component } from 'react';
import { Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import NavBar from './NavBar.jsx';

class Checkout extends Component {
  constructor(props) {
    super(props);
    console.log(this.props.bikes);
    this.state = {
      
    };

    this.confirmClick = this.confirmClick.bind(this);
    this.goBackClick = this.goBackClick.bind(this);
  }

  confirmClick() {
    this.props.history.push("/myBookings");
  }

  goBackClick() {
    this.props.history.push("/home");
  }

  render() {
    
    let btnstyle = "10px 0%";
    return (
      <div>

        <NavBar/>
          <Button onClick={this.confirmClick}>Confirm Booking</Button>
          <Button onClick={this.goBackClick}>Go Back</Button>

        // should display Card with the details of the bike which is selected. It should have two buttons i.e, confirm booking button and go back buttton
        
      </div>
    );
  }
}
export default Checkout;

标签: reactjs

解决方案


您可以像这样使用 history.push 传递数据:

this.props.propData.history.push({ 
 pathname: '/checkout',
 state: data_you_need_to_pass
});

并像这样从 /checkout 读取它:

const data = this.props.location.state;

你可以在这里阅读更多


推荐阅读