reactjs - 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;
解决方案
您可以像这样使用 history.push 传递数据:
this.props.propData.history.push({
pathname: '/checkout',
state: data_you_need_to_pass
});
并像这样从 /checkout 读取它:
const data = this.props.location.state;
你可以在这里阅读更多
推荐阅读
- python - 如何将 pandas 列中的浮点值离散为 [1, 10]
- swift - UITableView 中的行不会立即删除
- ssh - ssh:连接到主机 example.com 端口 22:权限被拒绝
- javascript - 如何从 JavaScript 读取 SharePoint 列表?
- c - 使用递归函数反转字符串的概念
- google-sheets - 这个公式的间接版本是什么?
- java - 使用 UTF8 编译 JAR
- reactjs - 如何更改道具 ReactJs
- windows - 启用记录到批处理文件命令
- wordpress - WP Query 将今天的日期与自定义字段日期进行比较以显示今天的生日