【问题标题】:How to return the boolean state value false to the parent in reactjs如何在reactjs中将布尔状态值false返回给父级
【发布时间】:2021-03-12 10:18:04
【问题描述】:

parent.tsx

const [modal, setModal] = useState(false);
const [detail, setDetail] = useState({});
<confirmation state={setModal(true)} data={detail} />

确认

return (
    <SweetAlert
      show={state}
      success
      title="Confirm"
      onConfirm={() => {return !state}}
    >
      I did it!
    </SweetAlert>
  )

点击确认时如何将布尔状态返回为假值? 因为我试图将值返回为 false,然后我尝试这个 onConfirm={() =&gt; {return !state}} 但它不起作用。

【问题讨论】:

  • 最后,你要做的就是通过 SweetAlert 将 Modal 状态设置为 false,为什么不将 setModal 作为 prop 传递并使用 prop 更改状态?跨度>

标签: javascript reactjs typescript next.js


【解决方案1】:

首先,always start your components with a capital letter。其次,一种简单的方法是将确认函数作为道具传递,然后使用。所以像:

<Confirmation state={setModal(true)} data={detail} onConfirm={() => setModal(false)} />

然后在Confirmation 组件中使用该道具:

return (
    <SweetAlert
      show={state}
      success
      title="Confirm"
      onConfirm={onConfirm}
    >
      I did it!
    </SweetAlert>
  )

这既简单又干净,使您的Confirmation 组件更易于重用,因为onConfirm 属性可以是任何东西

【讨论】:

  • 我还要补充一点,setModal(true) 将始终返回 undefined,我认为 OP 真正想要的是传递 modal
猜你喜欢
  • 2017-12-11
  • 2017-11-23
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
相关资源
最近更新 更多