为什么 destroyOnClose={true} 在 React 中不起作用

san*_*ndy 7 typescript reactjs antd ant-design-pro react-hooks

我正在使用 TypeScript 开发一个基于 React hook 的功能应用程序,并且我正在使用 ant design 的模态。我正在通过表格的模式提交表单。因此,将多次调用模式来填充表的不同行。

问题是,当模态弹出第二次、第三次或横向时,它总是携带之前的值。

为了避免这种情况,我在模态中设置了EnableViewState="false",它不起作用。我设置 destroyOnClose={true}。它不起作用。在模态文档中,写的是当destroyOnClose不起作用时我们需要使用。但在哪里定义它呢?因为,当我以模态形式设置为时 <Form onSubmit={props.inputSubmit} preserve={false},我收到一条错误消息Type '{ children: Element[]; onSubmit: any; preserve: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Form>......?

你用什么来让模态每次重新加载时,它都会重新加载为空?我不想在输入的表单值字段中分配状态。是否还有其他选项,例如 destroyOnClose={true} ?

这是我的模式,

<Form onSubmit={props.inputSubmit}>
  <Row>
    <Col span={10}>
      <Form.Item>
        <Text strong={true}>Article name: </Text>
      </Form.Item>
    </Col>
    <Col span={12}>
      <Form.Item>
        <Input
          style={{ backgroundColor: '#e6f9ff' }}
          name="articleName"
          onChange={props.handleArticleModalInput}
        />
      </Form.Item>
    </Col>
  </Row>
</Form>
Run Code Online (Sandbox Code Playgroud)

这是模态被调用的地方,

return (
  <>
    <ArticleTableModal
      destroyOnClose={true}
      isVisible={modalVisibilty}
      inputSubmit={inputSubmit}
      handleCancel={handleCancel}
      filledData={fetchedData}
      articleNumber={articleNumber}
      handleArticleModalInput={handleArticleModalInput}

    />

    <Table
      pagination={false}
      dataSource={articleDataSource}
      columns={articleColumns}
      scroll={{ y: 400 }}
      bordered
    />
  </>
)
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢。

Jar*_*ith 0

在这里,我们将使用一个自定义钩子,它包装来自其他地方(例如第 3 方 UI 库)的 ModalDialog 组件,并返回一个 setter 的元组和一个独立的组件/null。钩子使这变得更整洁,但您仍然可以使用类组件来完成所有这些,但代价是有点冗长。由于您标记了 Typescript,这应该很简单,但您可能必须指定使用 useState 是为了useState<React.ReactChild>();避免类型错误。

const useDialog = (ModalComponent) => {
  const [modalDialogState, setModalDialogState] = useState();
  return modalDialogState
    ? [
      setModalDialogState,
      // You may have to tweak this a bit depending on
      // how your library works.
      () => (
        <ModalComponent onClose={() => setModalDialogState('')> 
          {modalDialogState}
        </ModalComponent>
      ),
    ]
    : [setModalDialogState, null];
};

const MyComponent = () => {
  const [setModal, Modal] = useDialog(WhateverLibraryComponent);
  useEffect(() => {
    // Cleanup function, run on unMount and clears dialog contents.
    return () => setModal('');
  }, [setModal]);

  return Modal
    ? (
      <>
        <Modal />
        /* Normal render stuff */
      </>
    )
    // You can optionally render a button here with onClick
    // set to a function that calls setModal with some 
    // appropriate contents.
    : (/* Normal render stuff */)
};
    
Run Code Online (Sandbox Code Playgroud)