首页 > 文章列表 > React Ant Design Checkbox组件在编辑时无法初始化选中问题如何解决?

React Ant Design Checkbox组件在编辑时无法初始化选中问题如何解决?

151 2025-01-19

React Ant Design Checkbox组件在编辑时无法初始化选中问题如何解决?

react的ant design checkbox组件在编辑时无法初始化选中

问题中给出的react代码中存在checkbox无法在编辑时初始化选中的问题,这个问题可能由以下原因引起:

使用key属性初始化checkbox group

在给出的代码中,checkbox.group组件没有使用key属性。在react中,列表项必须具有唯一的key值。可以通过将itemsource中的项目映射到新的对象,并使用该对象的id或名称作为key,来解决此问题。修改后的代码如下:

{itemsource?.map((item, idx) => {
  return (
    <react.fragment key={+new date() + '_' + idx}>
      <row>
        <col span={24}>
          <div style={{ fontweight: 'bold', marginbottom: '10px' }}>{item.groupname}</div>
        </col>
      </row>
      <row>
        {item.protocolitemgrouplist?.map((item2, idx2) => {
          return (
            <react.fragment key={+new date() + '_' + idx + '_' + idx2}>
              <col span={6} style={{ display: 'inline-block' }}>
                <div style={{ marginbottom: '15px' }}>
                  <checkbox value={item2.id + '___' + item2.itemname}>{item2.itemname}</checkbox>
                </div>
              </col>
            </react.fragment>
          );
        })}
      </row>
    </react.fragment>
  );
})}

使用initialvalue初始化checkbox group

在checkbox.group组件中,可以使用initialvalue属性来初始化选中的值。修改后的代码如下:

<Checkbox.Group
  style={{ width: '100%' }}
  key={defaultCheckboxValue}
  initialValue={defaultCheckboxValue}
  onChange={(checkedValues) => onChangeCheckbox(checkedValues)}
>
  {/* ... */}
</Checkbox.Group>

通过以上修改,在编辑时应该就可以初始化选中checkbox。

来源:1731570397