简体   繁体   English

React 的 Hook 调用无效?

[英]Invalid Hook Call for React?

I'm trying to update the state of my component, but for some reason it keeps saying Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.我正在尝试更新我的组件的状态,但由于某种原因,它一直说Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

I'm trying to have a modal that opens onclick of a <div> .我正在尝试创建一个打开<div> onclick 的模式。 Within that modal is a text input that will update the state (notes).在该模态中是一个文本输入,它将更新状态(注释)。 For some reason it's saying invalid hook call - why is that?出于某种原因,它说无效的钩子调用 - 为什么会这样?

const openTestModal = () => {

  let [notes, setNotes] = useState("");
  let [openModal, setOpenModal] = useState(true);

  let modalBody =
    <div>
      <TextInput
        value={notes}
        onChange={(value) => setNotes(value)}
      />
    </div>

  return (
    <Modal
      open={openModal}
      onCancel={() => setOpenModal(false)}
      onConfirm={() => console.log('works')}
      body={modalBody}
    />
  )
};

const TestHooks = () => {

  return (
     <div onClick={() => openTestModal()}>
       Test
     </div>
  )
};

Seems like you tried to render testModal in react as an event, which's not a way to go, at all.似乎你试图将testModal渲染为一个事件,这根本不是一条路。 Instead you must render your testModal as component, like that, so click on Test div will open your modal:相反,您必须将您的testModal渲染为组件,就像那样,因此单击 Test div将打开您的模式:

const TestModal = () => {
  const [notes, setNotes] = useState("");

  const modalBody = (
    <div>
      <TextInput
        value={notes}
        onChange={(value) => setNotes(value)}
      />
    </div>
  )

  return (
    <Modal
      open={openModal}
      onCancel={() => setOpenModal(false)}
      onConfirm={() => console.log('works')}
      body={modalBody}
    />
  )
};

const TestHooks = () => {
  const [openModal, setOpenModal] = useState(false);
  return (
    <React.Fragment>
      <TestModal openModal={openModal} setOpenModal={setOpenModal} />
      <div onClick={() => setOpenModal(true)}>
        Test
      </div>
    <React.Fragment>
  )
};

Hope it helps :)希望能帮助到你 :)

It's not working because your testHooks is calling to setState from a separate component.它不起作用,因为您的 testHooks 正在从单独的组件调用 setState。 Add you testHooks code into your openTestModal component.将您的 testHooks 代码添加到您的 openTestModal 组件中。 It would work as is if TestHooks was a child of openTestModal as well.如果 TestHooks 也是 openTestModal 的子代,它也能正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM