React(Reakit):切换复选框时如何要求确认?

React (Reakit): How to ask for confirmation, when toggling a checkbox?

我想知道,是否有办法通过 Reakit's checkbox 请求确认。我正在使用 Reakit,因为我找到了一种快速的方法来读取数据库的布尔信息,但我也欢迎其他方法!

我习惯于使用带有 asyncwindow.confirm 的按钮进行确认:

<button onClick={async hiWhosebug => {
  if (window.confirm("Want to do this?")) {
    // saving to database here 
  }
}}>

但我不知道如何使用复选框来实现。简而言之,当用户切换 on/off 复选框时,我想让页面确认(然后保存到数据库)。

// personData = database table, with boolean "recurring"
// row = which entity in a table we are talking about

function CheckboxThing ({ row, personData }) {

  const checkbox = useCheckboxState({state: personData[row].recurring});

  return (
    <div className="checkbox-admin-other">
      <Checkbox 
        {...checkbox} 
        // what here?? onClick or something?
      />
    </div>
  );
}

Reakit的复选框可以这样使用:

const toggle = () => setChecked(!checked);
return <Checkbox checked={checked} onChange={toggle} />;

这意味着如果变量“checked”(需要放入 React 组件的状态)为 true,则复选框将被选中 并且当用户切换复选框时将调用名为“toggle”的方法。在该方法中,您可以放置​​将显示 确认提示 的代码,然后在用户单击 'Yes' 时更改选中状态,或者如果他们选中 'No' 则保持原样].

编码了一会儿之后,我找到了解决方案!事实证明,你可以把 async 放在 Reakit Checkbox 里面。感谢 Tomislav 和 Diego,他们的回答帮助我尝试了不同的东西并把它弄干净了!

完整函数如下:

// admin can edit the right to join back to the queue after getting to the front
function RecurringBox ({ row, personData }) {

  // sets the original values
  const checkbox = useCheckboxState({state: personData[row - 1].recurring});

  return (
    <Checkbox {...checkbox} onChange={async checkboxSwitch => {
      if (window.confirm("Change it?")) {

        checkboxSwitch.persist();

        // saving it to the database
        await put(`${process.env.API_PATH}/person`,
          {
            "id": personData[row - 1].id,
            "name": personData[row - 1].name,
            "recurring": checkboxSwitch.target.checked
          });
        reload(`${process.env.API_PATH}/person`);

      } else {
        return null;
      }
    }}/>
  );
}

您可以 "observe" 使用 React Hookscheckbox.state 进行更改:

function CheckboxThing({ row, personData }) {
  const checkbox = useCheckboxState({ state: personData[row].recurring });

  React.useEffect(() => {
    // checking if state has changed
    if (checkbox.state !== personData[row].recurring) {
      if (window.confirm("Want to do this?")) {
        // saving to database here
      } else {
        // revert checkbox state otherwise
        checkbox.setState(!checkbox.state);
      }
    }
  }, [checkbox.state, checkbox.setState, personData[row].recurring]);

  return (
    <div className="checkbox-admin-other">
      <Checkbox {...checkbox} />
    </div>
  );
}

如果您希望它在 UI 上的复选框状态更改之前打开,请改用 React.useEffect, the user will see the checkbox checked before window.confirm opens. But you can use React.useLayoutEffect