gpt4 book ai didi

javascript - antd react 中有没有解决方法来检查组件中未保存的更改?

转载 作者:行者123 更新时间:2023-12-05 06:55:28 29 4
gpt4 key购买 nike

我有一个名为 MyModal 的通用组件,它在我的网络应用程序中的近 20 多个组件中使用,我使用 ant-d modal。现在我必须检查 MyModal 的子组件中是否有任何未保存的更改:如果是,则提示用户。我可以通过使用新状态逐一检查每个子组件,但我不想这样做,感染我希望它从一个组件即 MyModal 组件是精确和可控的。

如何检查子组件中的状态变化(在 MyModal 中呈现)


我的代码结构

MyModal.js

import React, { Component } from 'react'
import { Modal } from 'antd'

class MyModal extends Component {
render() {
return (
<Modal {...this.props}>
{this.props.children}
</Modal>
)
}
}

export default MyModal

ChildComponent.js

import React, { Component } from 'react'
import { Input, Button } from 'antd'
import MyModal from '../components/MyModal'

class ChildComponent extends Component {
this.state = {
value: '',
visible: false,
};

onChangeValue = e => this.setState({ value: e.target.value });
toggleModal = () => this.setState({ visible: !this.state.visible });
handleOk = () => alert('hello world!')

render() {
const { visible, value } = this.state
return (
<div>
<Button onClick={this.toggleModal}>
Open Modal
</Button>
<MyModal visible={visible} onClose={this.toggleModal} footer={[
<Button key="back" onClick={this.toggleModal}>
Return
</Button>,
<Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
Submit
</Button>,
]}
>
<Input value={value} onChange={this.onChangeValue} />
{/* this is an example component to show you my problem, there are
a lot of more fields and states too. */}
</MyModal>
)
}
}

export default ChildComponent

最佳答案

我使用了 antd 中的 Form.Provider 并将所有子组件包装在 Form.Provider 中,如下所示。

  const changedFormsObj = {
accommodationForm: false,
userProfileForm: false,
}



<Form.Provider
onFormChange={(name) => {
changedFormsObj[name] = true;
}}
onFormFinish={(name) => {
changedFormsObj[name] = false;
}}
>
{children}
</Form.Provider>

当任何子表单组件发生变化时,onFormChange 方法将被 Form.Provider 中的表单名称触发,我们可以设置一个标志对于所有表单,当有表单提交时,将使用表单名称触发 onFormFinish 方法。有了这两个,我们可以决定是否为父组件本身的所有表单保存表单更改。

有关更多信息,请查看以下链接。

https://ant.design/components/form/#Form.Provider

关于javascript - antd react 中有没有解决方法来检查组件中未保存的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65335918/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com