javascript 是什么导致了这种奇怪的React

wko9yo5t  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(113)

在下面的example中,是什么原因导致按钮只有在它们都被选中后才被禁用?另外,由于状态在React中的工作方式,按钮在渲染时是否没有显示为禁用?

v09wglhw

v09wglhw1#

直接设置计算属性,避免冗余状态

export default function App() {
  const [tosChecked, setTosChecked] = useState(false);
  const [privacyChecked, setPrivacyChecked] = useState(false);

  function handleTOSChecked(e) {
    setTosChecked((c) => !c);
    // checkCanSubmit();
  }

  function handlePrivacyChecked(e) {
    setPrivacyChecked((c) => !c);
    //  checkCanSubmit();
  }

 // set property directly
 const enableSubmit = tosChecked && privacyChecked;

 return (
   ...
   <button
          // here 
          disabled={!enableSubmit}
          type="submit"
          className="btn inline-flex justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
        >

代码未按预期工作的可能原因是批量更新或需要反转禁用属性disabled={!canSubmit}

function handleTOSChecked(e) {
    setTosChecked(!tosChecked);
    // updates inside functions are batched and flushed out on next render cycle
    if (tosChecked && privacyChecked) {
      setCanSubmit(true);
    } else {
      setCanSubmit(false);
    }
    // the values of tosChecked and privacyChecked dont change
    // similar thing must be happing even if this code is inside a function called from this code
    console.log(tosChecked, privacyChecked);
}

希望能有所帮助

相关问题