簡體   English   中英

復選框未在與 Material-UI 的反應中切換

[英]Checkbox not toggling in React with Material-UI

所以我有一個 React 代碼,當我點擊它時,復選框沒有切換。

這是代碼框鏈接: https://codesandbox.io/s/inspiring-kirch-q6p4h

我正在初始化復選框 state,如下所示:

const [checkbox, setCheckBox] = useState(() => {
    let checkboxObj = {};

    rows.forEach((e) => {
      checkboxObj[e.id] = false;
    });
    return checkboxObj;
  });

我們有一個列數組,其中有一個名為 customElement 的 function,其中包含復選框處理程序。

const columns = [
    {
      key: "Source_campname",
      title: "TS Camp Name",
      customElement: function (row) {
        console.log(checkbox);
        return (
          <FormControlLabel
            control={
              <Checkbox
                checked={checkbox[row.id]}
                key={row.id}
                onChange={() =>
                  handleChange(row.Source_campname, row.id, checkbox)
                }
                name={row.id}
              />
            }
            label={[row.Source_campname]}
          />
        );
      }
    },
    {
      key: "Tracker_campname",
      title: "TR Camp Name"
    }
  ];

復選框切換在下面的 function 中處理:

const handleChange = (name, campid) => {
    setCheckBox({ ...checkbox, [campid]: !checkbox[campid] });
  };

發生的事情是當我點擊它時復選框沒有切換。 知道發生了什么嗎?

我對此進行了一些研究,並在將handleChange轉換為使用功能性 state 更新后

const handleChange = (name, campid) => {
  setCheckBox((checkbox) => ({
    ...checkbox,
    [campid]: !checkbox[campid]
  }));
};

為了嘗試避免將columns屬性傳遞給ThanosTable的任何陳舊外殼,我深入研究了該組件代碼,以查看它是否/如何處理在columns屬性中傳遞的重新封閉的復選框值。

問題

這些columns存儲在visibleColumns state 中的本地 state 中,ThanosTable 再也不會查看和響應columns ThanosTable的更改。

解決方案

添加useEffect以在 props 更新時更新visibleColumns state。

useEffect(() => {
  setVisibleColumns(
    !options.removeColumnsFeature &&
    options.showColumns &&
    options.showColumns.length
    ? [...columns.filter((x) => options.showColumns.includes(x.key))]
    : [...columns]
  )
}, [columns, options]);

編輯 checkbox-not-toggling-in-react-with-material-ui

您可以並且應該考慮visibleColumns state 初始化程序和效果回調之間的通用邏輯。

不要在useState聲明中使用回調

示例代碼sanbox

const [checkbox, setCheckBox] = useState({});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM