我正在学习反应,并试图创建一个汽车门户网站,其中根据汽车的可用性,用户可以通过单击按钮预订汽车。但是,当我单击按钮时,它会显示所有可用汽车的表单,如何仅显示按钮被单击的汽车的表单呢?
下面是我的App.js文件
import React from "react";
const cars = [
{
id: 1,
name: "Mruti",
price: 5.2,
available: false,
rental_price: 5000,
type: "Hatchback",
},
{
id: 2,
name: "Rnault",
price: 5.2,
available: true,
rental_price: 3000,
type: "SUV",
},
{
id: 3,
name: "Adi",
price: 5.2,
available: false,
rental_price: 5000,
type: "SUV",
},
{
id: 4,
name: "Hundai",
price: 209,
available: false,
rental_price: 100000,
type: "Luxury",
},
{
id: 5,
name: "Aton",
price: 500,
available: true,
rental_price: 500000,
type: "Luxury",
},
{
id: 6,
name: "Ercedes",
price: 35,
available: false,
rental_price: 50000,
type: "Sedan",
},
{
id: 7,
name: "BMW",
price: 32,
available: false,
rental_price: 50000,
type: "Hatchback",
},
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = { showForm: false };
}
showForm = () => {
return (
<div>
<form id="add-app">
<label>Price : </label>
<input type="text" />
<label> Hours : </label>
<input type="text" />
<button>Book</button>
</form>
</div>
);
};
render() {
return (
<div className="product">
{cars.map((car) => (
<div class="product_info">
<p key={car.id}>{car.name}</p>
<p key={car.id}>{car.price}</p>
<p key={car.id}>
{car.available === true ? (
<>
<p>Available</p>
<button
onClick={() => {
this.setState({showForm:true})
}}
>
Rent car
</button>
{this.state.showForm ? this.showForm() : null}
</>
) : (
<p>Unavailable</p>
)}
</p>
</div>
))}
</div>
);
}
}
export default App;
与其使用布尔状态(this.setState({ showForm: true })
),不如将汽车对象本身存储为状态(this.setState({ car })
)。
然后您可以检查状态中的汽车是否为空,而不是检查showForm
是否为真,并且您的showForm()
方法可以通过状态访问当前选择的汽车。
可以:
{this.state.showForm && (<this.showForm />)}
顺便说一句,你在类组件中使用功能组件有什么特殊的原因吗?
如果不是,我认为将它放在App
类中是低效的,因为它将为每个App
实例创建新的showForm
组件。