怎么将API的值填充到antd的Checkbox.Group中

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

How to fill value from API to checkbox.Group with antd

问题

我有一个数组menu来渲染所有的复选框和从API中检索到的数据对象。

目前,当返回数据为true时,我希望它被选中。

在这里显示数据的难点是要识别关键字,如果按照antd示例,它只是一个没有关键字的元素数组。

我知道Checkbox.Group有一个属性value用于填充数据,但我不知道如何处理它,请帮助我

const menu = [
  {
    label: "System",
    level: 1,
    view: true,
    add: true,
    edit: true,
    del: true,
    key: "agmdb"
  },
  {
    label: "Agent",
    level: 1,
    view: true,
    add: true,
    edit: true,
    del: true,
    key: "agent"
  },
  {
    label: "User",
    level: 2,
    view: true,
    add: true,
    edit: true,
    del: true,
    key: "users"
  }
];

从API检索到的数据对象

let userPermission = {
  agent: { view: true, edit: true, del: false, add: false },
  agmdb: { view: true, edit: false, del: true, add: false },
  users: { view: true, edit: false, del: false, add: true }
};

渲染菜单

const onChangeCheckbox = (arr, key) => {
  console.log(arr);
};

<div className="App">
  {menu.map((item) => {
    let arrKey = [
      userPermission[item.key]?.view ? `view` : "",
      userPermission[item.key]?.add ? `add` : "",
      userPermission[item.key]?.del ? `del` : "",
      userPermission[item.key]?.edit ? `edit` : ""
    ];
    return (
      <Form>
        <Form.Item
          style={{ margin: "10px 0" }}
          key={item.label}
          labelCol={{
            span: 6
          }}
          wrapperCol={{
            span: 12
          }}
          label={item.label}
        >
          <Checkbox.Group
            onChange={(e) => {
              onChangeCheckbox(e, item.key);
            }}
            value={arrKey}
          >
            <Checkbox value="view">
              View
            </Checkbox>
            <Checkbox value="add">
              Add
            </Checkbox>
            <Checkbox value="del">
              Delete
            </Checkbox>
            <Checkbox value="edit">
              Edit
            </Checkbox>
          </Checkbox.Group>
        </Form.Item>
      </Form>
    );
  })}
</div>

示例代码:https://codesandbox.io/s/busy-pine-n0iku4?file=/src/App.jsx

*更新:我已经为Checkbox.Group添加了value属性,并在检查条件时填充了数据,但有一个新问题,不能选中另一个框,您可以在codesandbox中查看。

英文:

I have an array menu to render all the checkbox and and a data object retrieved from the api.

Currently I want when the return data is true, it will be checked

The difficulty data to display here is the key keyword to identify, if according to antd example, it is just an element array without a key.

I know Checkbox.Group has 1 attribute value to fill data, but I don't know how to deal with it , pls help me

  const menu = [
{
label: &quot;System&quot;,
level: 1,
view: true,
add: true,
edit: true,
del: true,
key: &quot;agmdb&quot;
},
{
label: &quot;Agent&quot;,
level: 1,
view: true,
add: true,
edit: true,
del: true,
key: &quot;agent&quot;
},
{
label: &quot;User&quot;,
level: 2,
view: true,
add: true,
edit: true,
del: true,
key: &quot;users&quot;
}
];

Data object retrieved from the api:

  let userPermission = {
agent: { view: true, edit: true, del: false, add: false },
agmdb: { view: true, edit: false, del: true, add: false },
users: { view: true, edit: false, del: false, add: true }
};

Render Menu:

 const onChangeCheckbox = (arr, key) =&gt; {
console.log(arr);
};
&lt;div className=&quot;App&quot;&gt;
{menu.map((item) =&gt; {
let arrKey = [
userPermission[item.key]?.view ? `view` : &quot;&quot;,
userPermission[item.key]?.add ? `add` : &quot;&quot;,
userPermission[item.key]?.del ? `del` : &quot;&quot;,
userPermission[item.key]?.edit ? `edit` : &quot;&quot;
];
return (
&lt;Form&gt;
&lt;Form.Item
style={{ margin: &quot;10px 0&quot; }}
key={item.label}
labelCol={{
span: 6
}}
wrapperCol={{
span: 12
}}
label={item.label}
&gt;
&lt;Checkbox.Group
onChange={(e) =&gt; {
onChangeCheckbox(e, item.key);
}}
value={arrKey}
&gt;
&lt;Checkbox value=&quot;view&quot;&gt;
View
&lt;/Checkbox&gt;
&lt;Checkbox value=&quot;add&quot;&gt;
Add
&lt;/Checkbox&gt;
&lt;Checkbox value=&quot;del&quot;&gt;
Delete
&lt;/Checkbox&gt;
&lt;Checkbox value=&quot;edit&quot;&gt;
Edit
&lt;/Checkbox&gt;
&lt;/Checkbox.Group&gt;
&lt;/Form.Item&gt;
&lt;/Form&gt;
);
})}
&lt;/div&gt;

example code : https://codesandbox.io/s/busy-pine-n0iku4?file=/src/App.jsx

*UPDATE: i have add the value to checkbox.Group and it filled the data when checking the condition, there is a new problem that can't check another box, you can see it in codesanbox

答案1

得分: 1

使用复选框组件时,请使用名称而不是值。

<Checkbox name="view">

并使用表单钩子...

const [form] = Form.useForm();
<Form form={form}>

并且你应该使用

form.setFieldsValue()

来填充输入。

英文:

use name instead of value in checkbox component.

&lt;Checkbox name=&quot;view&quot;&gt;

and use form hook ...

const [form] = Form.useForm();
&lt;Form form={form}&gt;

and u should use

form.setFieldsValue()

to fill inputs

答案2

得分: 1

使用 Form 来使其工作,您需要将 name 属性指定为 Form.Item。在您的情况下,name 将是 agmdbagentusers

在 useEffect 中,获取所有的 userPermissions,并在必要时将其存储在一个状态中。复选框组的值格式应该是一个字符串数组 [ 'view', 'edit' ]。但是 userPermission 有一个不同的格式,其中值是键值对。因此,我们需要过滤出那些具有值为 true 的键。然后在表单中设置这些值。由于每个复选框组有4个选项,所以我创建了一个包含标签和值的选项数组。如果需要,您还可以在选项中使用 disabled。在提交时,您可能需要原始数据格式。我还编写了一段代码,将值转换为原始格式。希望这能解决您的问题。

英文:

To make it work using Form, you need to specify name prop to Form.Item. In your case, name will be agmdb, agent, users.

In useEffect, get all the userPermissions and store it in a state if required. Checkbox group value format should be an array of string [&#39;view&#39;, &#39;edit&#39;]. But userPermission have a different format where value is key value pair. So we need to filter out those keys that have value true.
Then set the values in form. Since each Checkbox.Group have 4 options so i created an options array of label and value. You can also use disabled in options if you need that. On submit, you may required the original data format. I also write a code that will convert the values into original format.
Hope this solves your problem

import { useEffect } from &#39;react&#39;;
import { Button, Checkbox, Form } from &#39;antd&#39;;
const menu = [
{ label: &#39;System&#39;, level: 1, view: true, add: true, edit: true, del: true, key: &#39;agmdb&#39; },
{ label: &#39;Agent&#39;, level: 1, view: true, add: true, edit: true, del: true, key: &#39;agent&#39; },
{ label: &#39;User&#39;, level: 2, view: true, add: true, edit: true, del: true, key: &#39;users&#39; }
];
const userPermission = {
agent: { view: true, edit: true, del: false, add: false },
agmdb: { view: true, edit: false, del: true, add: false },
users: { view: true, edit: false, del: false, add: true }
};
const options = [
{ label: &#39;View&#39;, value: &#39;view&#39; },
{ label: &#39;Add&#39;, value: &#39;add&#39; },
{ label: &#39;Edit&#39;, value: &#39;edit&#39; },
{ label: &#39;Delete&#39;, value: &#39;del&#39; }
];
const App = () =&gt; {
const [form] = Form.useForm();
useEffect(() =&gt; {
// Fetch userPermission from API
// Each Checkbox.Group value is an array of string (true means checked)
// Example: { agmdb: [&#39;view&#39;, &#39;del&#39;], agent: [&#39;view&#39;], users: [&#39;view&#39;, &#39;add&#39;] }
const data: Record&lt;string, Array&lt;string&gt;&gt; = {};
Object.entries(userPermission).forEach(([key, value]) =&gt; {
data[key] = Object.keys(value).filter((key) =&gt; value[key as keyof typeof value]);
});
form.setFieldsValue(data);
}, [form]);
const onFinish = (values: any) =&gt; {
const finalData: Record&lt;string, Record&lt;string, boolean&gt;&gt; = {};
Object.entries(values).forEach(([key, value]: any) =&gt; {
finalData[key] = value.reduce((acc: any, cur: string) =&gt; {
acc[cur] = true;
return acc;
}, {});
});
console.log(finalData);
};
return (
&lt;div className=&#39;App&#39;&gt;
&lt;Form form={form} onFinish={onFinish}&gt;
{menu.map((item) =&gt; {
return (
&lt;Form.Item
key={item.key}
style={{ margin: &#39;10px 0&#39; }}
labelCol={{ span: 6 }}
wrapperCol={{ span: 12 }}
label={item.label}
name={item.key}
&gt;
&lt;Checkbox.Group options={options} /&gt;
&lt;/Form.Item&gt;
);
})}
&lt;Button htmlType=&#39;submit&#39;&gt;Submit&lt;/Button&gt;
&lt;/Form&gt;
&lt;/div&gt;
);
};
export default App;

huangapple
  • 本文由 发表于 2023年2月6日 11:39:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357137.html
匿名

发表评论

匿名网友

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

确定