【发布时间】:2021-10-17 13:22:15
【问题描述】:
这就是我现在拥有的。
除重置按钮外的每一行都是一个名为Item 的子组件。一个项目有一个指示其计数的徽章,2 个用于递增、递减的按钮和一个 delete 按钮。名为ItemList 的父组件包含重置按钮和子组件。由于父级维护子级列表,因此删除功能也在父级中实现。除了reset 按钮之外,我所需的所有功能都已完成。
重置按钮可以被认为是一个主按钮&应该能够在点击时重置所有孩子的count。计数由每个孩子维护为状态,因此理想情况下,父母应该调用列表中包含的每个孩子的重置函数,但我无法为这个特定部分提供代码。我不确定如何访问每个孩子的重置功能并将其应用于列表中的所有孩子。
项目代码(子项)
function Item({ deleteHandler }) {
const [count, setCount] = useState(0);
const [cName, setCName] = useState("badge bg-warning text-dark");
useEffect(() => {
setCName(count !== 0 ? "badge bg-primary" : "badge bg-warning text-dark");
}, [count]);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
const decrement = () => {
setCount((prevCount) => prevCount - 1);
};
//this is what needs to be called
const reset = () => {
setCount(0);
};
const zero = "zero";
return (
<div style={{ marginTop: "10px" }}>
<span style={{ marginRight: "10px" }} className={cName}>
{count !== 0 ? count : zero}
</span>
<button
style={{ marginRight: "5px" }}
className="btn btn-secondary btn-sm"
onClick={increment}
>
+
</button>
<button
style={{ marginRight: "5px" }}
className="btn btn-secondary btn-sm"
onClick={decrement}
>
-
</button>
<button onClick={deleteHandler} className="btn btn-danger btn-sm">
Delete
</button>
</div>
);
}
export default Item;
ItemList(父级)的代码
function ItemList() {
const [items, setItems] = useState([Item, Item, Item]);
const deleteItem = (index) => {
alert(index);
var temp = [...items]; //create new copy
temp.splice(index, 1);
setItems(temp);
};
const resetAll = () => {
//this is where I need to call reset() on all the items (children)
};
return (
<div>
<div style={{ marginTop: "10px" }}>
<button className="btn btn-primary" onClick={resetAll}>
Reset
</button>
{items.map((MyItem, index) => {
return (
<div key={index}>
<MyItem deleteHandler={() => deleteItem(index)} />
</div>
);
})}
</div>
</div>
);
}
export default ItemList;
【问题讨论】:
-
另一种方法是使用
ItemList组件中的状态作为单一事实来源。这消除了对每个 Item 组件中的状态的需要。 codesandbox.io/s/cool-dust-3qc4k?file=/src/App.js
标签: javascript reactjs components