React JS:如何将数据从一个组件发送到另一个组件onClick事件



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

自行车卡.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;

Checkout.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;

您可以使用history.push传递数据,如下所示:

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

然后像这样从/结账:

const data = this.props.location.state;

你可以在这里阅读更多

最新更新