我有一個簡單的部分,其中包含具有多個復選框和默認價格的產品,我希望當復選框為真時顯示其價格并洗掉所有其他價格明顯為錯誤狀態的價格。如果所有復選框都為假,則顯示所有價格
現場演示:現場演示
這是我到目前為止所擁有的 //toppings.js
export const toppings = [
{
name: "Capsicum",
price: 1.2
},
{
name: "Paneer",
price: 2.0
},
{
name: "Red Paprika",
price: 2.5
},
{
name: "Onions",
price: 3.0
},
{
name: "Extra Cheese",
price: 3.5
},
{
name: "Baby Corns",
price: 3.0
},
{
name: "Mushroom",
price: 2.0
}
];
這是我的解決方案
import { toppings } from "./utils/toppings";
export default function App() {
const [checkedState, setCheckedState] = useState(
new Array(toppings.length).fill(false)
);
const handleOnChange = (position) => {
const updatedCheckedState = checkedState.map((item, index) =>
index === position ? !item : item
);
setCheckedState(updatedCheckedState);
const elements = updatedCheckedState.filter((currentState, index) => {
if (currentState === false) {
delete toppings[index].price;
} else if (currentState === false) {
toppings[index] = toppings[index].price;
console.log("current state", currentState);
}
return 0;
});
console.log(elements);
};
return (
<div className="App">
<ul className="toppings-list">
{toppings.map(({ name, price }, index) => {
return (
<li key={index}>
<div className="toppings-list-item">
<div className="left-section">
<input
type="checkbox"
id={`custom-checkbox-${index}`}
name={name}
value={name}
checked={checkedState[index]}
onChange={() => handleOnChange(index)}
/>
<label htmlFor={`custom-checkbox-${index}`}>{name}</label>
</div>
</div>
</li>
);
})}
</ul>
<ul className="toppings-list">
{toppings.map(({ name, price }, index) => {
return <li key={index}> {price} </li>;
})}
</ul>
</div>
);
}
不幸的是,這沒有按預期作業,有人可以告訴我這里做錯了什么
uj5u.com熱心網友回復:
這是一個簡單的作業示例。將所有選定的專案索引存盤在狀態陣列中
現場示例 - https://codesandbox.io/s/condescending-sara-t5ws3?file=/src/App.js
import { useState } from "react";
import { toppings } from "./utils/toppings";
import "./styles.css";
export default function App() {
const [checked, setChecked] = useState([]);
const handleChecked = (e, index) => {
let prev = checked;
let itemIndex = prev.indexOf(index);
if (itemIndex !== -1) {
prev.splice(itemIndex, 1);
} else {
prev.push(index);
}
setChecked([...prev]);
};
return (
<div className="App">
<ul className="toppings-list">
{toppings.map(({ name, price }, index) => {
return (
<>
<li key={index}>
<div className="toppings-list-item">
<span className="left-section">
<input
type="checkbox"
id={`custom-checkbox-${index}`}
// name={name}
// value={name}
checked={checked.includes(index)}
onChange={(e) => handleChecked(e, index)}
/>
<label htmlFor={`custom-checkbox-${index}`}>{name}</label>
</span>
{(!checked.length || checked.includes(index)) && (
<span>{price}</span>
)}
</div>
</li>
</>
);
})}
</ul>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377968.html
標籤:javascript 数组 反应 反应钩子
