如何从一个函数中调用React组件的函数元素?

huangapple go评论69阅读模式
英文:

How to invoke React Component function element from a function?

问题

以下是您要翻译的内容:

我有下面的函数,该函数在单击编辑按钮时调用显示模态对话框。如何从函数showModal中渲染功能组件UpdateModal

以下是该函数:

```tsx
const showModal = (user: IUser) => {
  setShowUpdateModal(true);
  return (
    <>
      <div>Hello</div>
      <UpdateModal
      
        showUpdateModal={showUpdateModal}
        setShowUpdateModal={
          (bool: boolean | ((prevState: boolean) => boolean)) => 
            setShowUpdateModal(bool)
        }
      />
    </>
  );
}

UpdateModal:



const UpdateModal: FC<updateModalProps> = ({
  setShowUpdateModal,
  showUpdateModal,
  user
}) => {
  console.log("showUpdateModal....", showUpdateModal);
  return (
    <Modal showUpdateModal={showUpdateModal}>
      <Modal.Dialog>
        <Modal.Header closeButton onClick={() => setShowUpdateModal(false)}>
          <Modal.Title className={`${styles.createText}`}>
            创建用户表单
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <UpdateUser user={user} setShowUpdateModal={setShowUpdateModal} />
        </Modal.Body>
      </Modal.Dialog>
    </Modal>
  );
}

export default UpdateModal;

<details>
<summary>英文:</summary>

I have the below function which calls show a modal dialog on click of edit button. How do I render the functional component `UpdateModal` from function showModal?

Here is the function:

```tsx
const showModal = (user: IUser) =&gt; {
  setShowUpdateModal(true);
  return (
    &lt;&gt;
      &lt;div&gt;Hello&lt;/div&gt;
      &lt;UpdateModal
      
        showUpdateModal={showUpdateModal}
        setShowUpdateModal={
          (bool: boolean | ((prevState: boolean) =&gt; boolean)) =&gt; 
            setShowUpdateModal(bool)
        }
      /&gt;
    &lt;/&gt;
  );
}

UpdateModal:



const UpdateModal: FC&lt;updateModalProps&gt; = ({
  setShowUpdateModal,
  showUpdateModal,
  user
}) =&gt; {
  console.log(&quot;showUpdateModal....&quot;, showUpdateModal);
  return (
    &lt;Modal showUpdateModal={showUpdateModal}&gt;
      &lt;Modal.Dialog&gt;
        &lt;Modal.Header closeButton onClick={() =&gt; setShowUpdateModal(false)}&gt;
          &lt;Modal.Title className={`${styles.createText}`}&gt;
            Create User Form
          &lt;/Modal.Title&gt;
        &lt;/Modal.Header&gt;
        &lt;Modal.Body&gt;
          &lt;UpdateUser user={user} setShowUpdateModal={setShowUpdateModal} /&gt;
        &lt;/Modal.Body&gt;
      &lt;/Modal.Dialog&gt;
    &lt;/Modal&gt;
  );
}

export default UpdateModal;

答案1

得分: 0

问题在于你不能从回调函数中返回JSX,并期望React知道它需要在某个地方渲染它。

showModal回调可以更新showUpdateModal状态,并且父组件将使用更新后的状态值重新渲染。从这里,你只需将模态框作为父组件的渲染返回的一部分呈现出来。

更新showUpdateModal状态以保存对特定用户的引用,或者将其设置为null值。将此传递给模态框的user属性。关闭模态框的所有操作都应将showUpdateModal状态设置回null以关闭模态框。

示例:

function UserContent() {
  const [showUpdateModal, setShowUpdateModal] = useState<IUser | null>(null);

  const showModal = (user: IUser) => {
    setShowUpdateModal(user);
  };

  // ...

  return (
    <>
      <div>
        <Table responsive striped bordered hover variant="light">
          {/* ... */}
          <Pen
            color="black"
            size={20}
            onClick={() => showModal(user)} // <-- 打开模态框
          />
          {/* ... */}
        </Table>
      </div>

      <UpdateModal
        user={showUpdateModal} // 用户或null
        showUpdateModal={!!showUpdateModal} // <-- 打开/关闭模态框
        setShowUpdateModal={setShowUpdateModal}
      />

      {/* ... */}
    </>
  );
}
type updateModalProps = {
  setShowUpdateModal: (user: IUser | null) => void;
  showUpdateModal: IUser | null;
  user: IUser;
};

const UpdateModal: FC<updateModalProps> = ({
  setShowUpdateModal,
  showUpdateModal,
  user
}) => {
  return (
    <Modal show={!!showUpdateModal}>
      <Modal.Dialog>
        <Modal.Header closeButton onClick={() => setShowUpdateModal(null)}>
          <Modal.Title className={`${styles.createText}`}>
            Create User Form
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <UpdateUser user={user} setShowUpdateModal={setShowUpdateModal} />
        </Modal.Body>
      </Modal.Dialog>
    </Modal>
  );
}
英文:

The issue is that you can't return JSX from a callback function and expect React to know it needs to render it somewhere.

The showModal callback can update the showUpdateModal state and the parent component will be rerendered with the updated state value. From here you just render the modal as part of the render return of the parent component.

Update the showUpdateModal state to hold a reference to a specific user, or a null value. Pass this to the modal's user prop. All the modal closing actions should set the showUpdateModal state back to null to close the model.

Example:

function UserContent() {
  const [showUpdateModal, setShowUpdateModal] = useState&lt;IUser | null&gt;(null);

  const showModal = (user: IUser) =&gt; {
    setShowUpdateModal(user);
  };

  ...

  return (
    &lt;&gt;
      &lt;div&gt;
        &lt;Table responsive striped bordered hover variant=&quot;light&quot;&gt;
          ...
          &lt;Pen
            color=&quot;black&quot;
            size={20}
            onClick={() =&gt; showModal(user)} // &lt;-- toggles modal open
         /&gt;
          ...
        &lt;/Table&gt;
      &lt;/div&gt;

      &lt;UpdateModal
        user={showUpdateModal} // user or null
        showUpdateModal={!!showUpdateModal} // &lt;-- toggles modal open/close
        setShowUpdateModal={setShowUpdateModal}
      /&gt;

      ...
    &lt;/&gt;
  );
}
type updateModalProps = {
  setShowUpdateModal: (user: IUser | null) =&gt; void;
  showUpdateModal: IUser | null;
  user: IUser;
};

const UpdateModal: FC&lt;updateModalProps&gt; = ({
  setShowUpdateModal,
  showUpdateModal,
  user
}) =&gt; {
  return (
    &lt;Modal showUpdateModal={showUpdateModal}&gt;
      &lt;Modal.Dialog&gt;
        &lt;Modal.Header closeButton onClick={() =&gt; setShowUpdateModal(null)}&gt;
          &lt;Modal.Title className={`${styles.createText}`}&gt;
            Create User Form
          &lt;/Modal.Title&gt;
        &lt;/Modal.Header&gt;
        &lt;Modal.Body&gt;
          &lt;UpdateUser user={user} setShowUpdateModal={setShowUpdateModal} /&gt;
        &lt;/Modal.Body&gt;
      &lt;/Modal.Dialog&gt;
    &lt;/Modal&gt;
  );
}

答案2

得分: 0

我认为你需要在UserContent的返回值中有条件地渲染UpdateModal组件。从概念上讲,这是最常见的流程:

const UpdateModal = (...) => {...}

const UserContent = (...) => {
  const [showUpdateModal, setShowUpdateModal] = useState(false);

  return (
    <>
      {showUpdateModal ? <UpdateModal /> : null}
      ...
      <Pen color="black" size={20} onClick={() => { setShowUpdateModal(true); }} />

    </>

  )
}

这段代码将在点击Pen时触发重新渲染,因为状态发生了变化。然后,因为showUpdateModaltrueUpdateModal将被渲染。然而,这将需要你对代码进行重大重新组织。

英文:

I think you need to conditionally render the UpdateModal component in the returned value of UserContent. Conceptually this is the flow most often seen:

const UpdateModal = (...) =&gt; {...}

const UserContent = (...) =&gt; {
  const [showUpdateModal, setShowUpdateModal] = useState(false);

  return (
    &lt;&gt;
      {showUpdateModal ? &lt;UpdateModal /&gt; : null}
      ...
      &lt;Pen color=&quot;black&quot; size={20} onClick={() =&gt; { setShowUpdateModal(true); }} /&gt;

    &lt;/&gt;

  )
}

This code will trigger rerender when clicking Pen because state changes. Then, because showUpdateModal is true, UpdateModal will be rendered. However this will require you to reorganize your code significantly.

huangapple
  • 本文由 发表于 2023年6月22日 15:21:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529454.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定