[英]Material-UI Nested Checkbox selection doesn't render change to parent in DOM
我有一個正在工作的嵌套復選框示例,我正在將其實現到我的應用程序中。 復選框的邏輯功能足以涵蓋這 7 種情況
- Scenario - No children, no parent selected
- Select the parent -> select the parent and all children
- Select a child -> select that child and its parent
- Scenario - All children and the parent selected
- Select the parent -> deselect the parent and all children
- Select a child -> deselect only that child
- Scenario - Some children and the parent selected
- Select the parent -> select all unselected children
- Select a child -> select that child, parent remains selected
- Deselect last child -> deselect the child and deselect the parent
我遇到的問題是,在選擇或取消選擇子項的情況下,父復選框的 state 會更新,但復選框的實際視覺變化並未發生。
從我的代碼:
<Checkbox
disableRipple
edge="start"
checked={sub.checked}
onChange={() =>
this.handleCheckClick(sub.id, parentIndex)
}
/>
Material-UI <Checkbox />
組件位於項目列表中,每個項目都有一個后續項目列表,每個項目都有自己的<Checkbox />
組件。 當我 select 列表的父復選框 state 通過該handleCheckClick()
方法正確更改時,state 已正確更新,並且視覺更新發生為
單擊子級時,理想的情況是然后選擇父級,它位於反應組件的 state 中,但是盡管復選框的checked
state 被映射到 Z9ED36E2EA9942EF5786B,但視覺方面並沒有發生變化。
有趣的是,如果我使用這樣的本機輸入:
<input
type="checkbox"
disableRipple
edge="start"
checked={sub.checked}
onChange={() =>
this.handleCheckClick(sub.id, parentIndex)
}
/>
正確的行為既顯示在視覺上,也顯示在 state 中(就像它已經是一樣)。 我不確定這是特定於 Material-UI 的錯誤,還是競爭條件,或發生了其他事情,但我知道handleCheckClick()
function 中的邏輯是合理的,因為在反應 Z9ED39E2EA93158EF57B36A9 中正確顯示了更改。
您實際上有一個警告指示正在發生的事情:
警告:組件正在更改要控制的復選框類型的不受控制的輸入。 輸入元素不應從不受控切換到受控(反之亦然)。 決定在組件的生命周期內使用受控輸入元素還是不受控輸入元素。 更多信息: https://reactjs.org/docs/forms.html#controlled-components
問題是您沒有在createSubscriptions
中初始化checked
的 state (請參見下面的代碼),因此最初sub.checked
是undefined
。 這會導致 Material-UI 將復選框視為不受控制的,因此稍后指定checked
的 state 無效。
function createSubscriptions() {
const statusSet = ["Processing", "Completed", "Submitted", "Error"];
const quantity = (faker.random.number() % 10) + 1;
const subscriptions = [];
let x = 0;
while (x < quantity) {
subscriptions.push({
id: faker.random.uuid(),
name: faker.lorem.words(),
description: faker.lorem.sentence(),
created: faker.date.past(),
status: statusSet[faker.random.number() % 4],
checked: false, // ADDING THIS FIXES IT
geoJson: {
features: createGeoJson()
}
});
x += 1;
}
return subscriptions;
}
或者,您可以在呈現復選框時處理此問題:
<Checkbox
disableRipple
edge="start"
checked={sub.checked || false}
onChange={() =>
this.handleCheckClick(sub.id, parentIndex)
}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.