【发布时间】:2020-04-26 06:11:03
【问题描述】:
我正在用 React 创建我的第一个应用程序。这是一个电影院预订应用程序。我有一个组件,它是放映室中的单个座位,以及一个带有座位列表和预订的放映室组件。我需要访问用户将选择的座位 ID,并在单击提交按钮后将此数据发送到 api。我现在这样做的方式行不通。我认为这是因为我没有在screeningRoom 组件中呈现单个座位,而是在列表中呈现。
这是我的代码:
座椅组件
import React, { Component } from "react";
import "./seat.css";
class Seat extends Component {
constructor(props) {
super(props);
this.state = {
bgc: this.props.ticket ? "red" : "grey",
seatId: ""
};
//console.log(this.props)
}
reserve = () => {
if (!this.props.ticket) {
this.state.bgc === "grey"
? this.setState({ bgc: "green" })
: this.setState({ bgc: "grey" });
}
this.setState({ seatId: this.props.id });
//console.log (this.props.id)
};
render() {
return (
<div>
<input
className="seat"
style={{ backgroundColor: this.state.bgc }}
onClick={this.reserve}
></input>
</div>
);
}
}
export default Seat;
screeningRoom 组件
import React, { Component } from "react";
import axios from "axios";
import Seat from "./seats";
import "./screeningRoom.css";
export default class screeningRoom extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
seats: [],
room: [],
clicked: []
};
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async componentDidMount() {
this.setState({ loading: true });
const {
match: { params }
} = this.props;
const res = await axios.get(
`http://localhost:8080/api/shows/${params.id}/seats`
);
//console.log(res)
this.setState({ seats: res.data.seats });
//console.log(this.state.seats)
this.setState({ room: res.data.name });
}
renderSeats() {
return this.state.seats.map(seat => (
<Seat
onClick={this.handleClick.bind(this)}
key={seat._id}
value={seat._id}
ticket={seat.ticket}
seat={seat}
/>
));
}
handleSubmit(e) {
e.preventDefault();
console.log(e.target.value);
}
handleClick(e) {
console.log(e.currentTarget.value);
}
render() {
return (
<div
className="screening-room d-flex flex-column justify-contnt-center align-items-center"
style={{ marginTop: 20 }}
>
<h3 style={{ color: "white" }}>Room: {this.state.room} </h3>
<div className="screen">screen</div>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className={this.state.room}>{this.renderSeats()}</div>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
【问题讨论】:
-
使用事件
target是一种低效的数据处理方式,你已经知道值了,直接使用即可。onClick={() => this.handleClick(value)}
标签: javascript reactjs