首先,我真的读过几十个类似的问题,但仍然无法为我的问题找到任何可行的解决方案。也许解决方案并不那么复杂,但我是 React 的初学者,没有足够的经验来处理它。
我有一个 ManagePage.js它是一个功能组件,并使用 React Hooks 作为其状态。它适用于在表格中呈现所有设备,显示更新/删除的 An't Modal ,以及当您想从列表中删除设备时发出警告(我才开始实现从状态中创建/更新/删除设备的功能(。它看起来像这样:
import React, { useState } from "react";
import { Layout, Input, Space, Table } from "antd";
import ManageItem from "../components/ManageItem";
const ManagePage = () => {
const [devices, setDevices] = useState([
{
id: "some_id",
type: "some type",
name: "Some Name",
value: 123,
},
{
id: "some_id2",
type: "some type2",
name: "Some Name2",
value: 1234,
},
]);
function removeDevice(id) {
setDevices(devices.filter((e) => e.id !== id));
}
const data = devices.flatMap((device) => [
{
id: device.id,
type: device.type,
name: device.name,
value: device.value,
actions: (
<ManageItem
deviceId={device.id}
deviceType={device.type}
deviceName={device.name}
deviceValue={device.value}
onRemoveDevice={removeDevice}
/>
),
},
]);
return (
<div className={"manage-container"}>
<Layout.Content>
<Space direction="vertical">
<h1>Manage</h1>
<div className={"manage-add-remove-device"}>
{" "}
<div className={"manage-add-new-device"}>
<ManageItem />
</div>
<Input.Search
className={"manage-search-device"}
placeholder="find device"
onSearch={(value) => console.log(value)}
enterButton
/>
</div>
</Space>
<Table
rowkey={(record) => record.id}
columns={columns}
dataSource={data}
onChange={onChange}
/>
</Layout.Content>
</div>
);
};
如您所见,我正在使用 and.design(因为 Cube.js 适用于它(。这是子组件:
import React from "react";
import { Input, Modal, Form, Button, Select, Tooltip } from "antd";
class ManageItem extends React.Component {
constructor(props) {
super(props);
this.showForm = this.showForm.bind(this);
this.showDeleteConfirm = this.showDeleteConfirm.bind(this);
}
state = { isFormVisible: false };
showDeleteConfirm = () => {
Modal.confirm({
title: "Are you sure you want to do this?",
icon: <ExclamationCircleOutlined />,
content: `Device "${this.props.deviceName}" with ID "${this.props.deviceId}" will be removed from this list.`,
onOk: onRemoveDevice(this.props.deviceId),
onCancel() {
console.log("Cancel");
},
});
};
showForm = () => {
this.setState({
isFormVisible: true,
});
};
return (
<div>
{this.props.deviceId ? (
<Tooltip title="remove device">
<a
onClick={this.showDeleteConfirm}
className={"manage-remove-device"}
>
<CloseSquareOutlined />
</a>
</Tooltip>
</div>
) : (
<a onClick={this.showForm}>
<h3>
<PlusSquareOutlined /> Add new device
</h3>
</a>
)}
{.........}
);
}
}
export default ManageItem;
我想要的只是在孩子的showDeleteConfirm
中使用onOk:
从父母中删除选定的设备。如果您有任何其他建议,如何改进我的代码我将很高兴听到!
我认为在您的管理项子组件中,您应该像下面这样调用onOk。
onOk:()=>{this.props.onRemoveDevice(this.props.deviceId)}
bcz 你已经传递删除设备从父级到子级,即管理项目
您可以尝试将showDeleteConfirm 函数移动到父级上,从子项中删除并使用props.function从子项中调用,添加"PropTypes",您可以阅读以下内容: 道具类型