在React中将功能组件从子组件传递到父组件

时间:2020-10-07 15:41:11

标签: javascript reactjs dynamic modal-dialog

是否可以将功能组件从子组件传递到父组件?我正在尝试做一个动态模态,该模态显示在父级内部,但子级可以通过提供程序中的函数进行填充,例如:

setModal(() => (
    <div>content</div>)
)

父级收到此组件:

const [modal, setModal] = useState(false)
const [modalContent, setModalContent] = useState<FunctionComponent>()
...
<Provider value={{
    setModal: (content: FunctionComponent) => {
        setModalContent(content); // This updates the state to hold a function component and to re-render
        setModal(true); // This updates a state flag to show the overlay in which the modal is rendered
    },
}}>
...
</Provider>

模态的内容应该是动态的。我试图使用组件的状态来保存功能组件,但是我不认为这是可行的还是一种好习惯。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,您仍然希望将功能从父级传递给每个孩子,但每个孩子都应该能够更改父级也拥有所有权的模态组件的状态。

对于上述情况,您可以执行以下操作:

const Provider = ({ children, updateModal }) => {
  // With this, every child has the ability to call updateModal
  return React.Children(children).map(child => cloneElement(child, { updateModal }));
};

const ModalComponent = ({ open, children }) => {
  if (!open) return null;

  return (
    <dialog>
      {children}
    </dialog>
  );
};

const ParentComponent = () => {
  const [modal, setModal] = useState(false);
  const [modalContent, setModalContent] = useState(null);

  const updateModal = (content) => {
    setModalContent(content);
    setModal(true);
  };

  return (
    <>
      <Provider updateModal={updateModal}>
        {...insert children here}
      </Provider>
      <ModalComponent open={modal}>
        {modalContent}
      </ModalComponent>
    </>

  );
};
相关问题