首页 > 解决方案 > 如何在 Cascader Ant Design ReactJs 中显示子项?

问题描述

我在如何在 console.log 下方显示 categorySubResponses 和 categorySubChildResponses 的数据时遇到问题

在此处输入图像描述

像这种级联的梦取自虚拟数据

在此处输入图像描述

现在没有孩子

在此处输入图像描述

我用蚂蚁设计https://ant.design/components/cascader/

我把代码codesanbox.io和链接

https://codesandbox.io/embed/q-56619059-so-8dk0z

标签: javascriptreactjs

解决方案


您需要为每个数组创建值和标签.map() categorySubResponsescategorySubResponses

const options = this.state.allCategory.map(category => ({
  value: category.id,
  label: category.name,
  children: category.categorySubResponses && category.categorySubResponses.map(child => ({
    value: child.id,
    label: child.name,
    children: child.categorySubChildResponses && child.categorySubChildResponses.map(innerChild => ({
      value: innerChild.id,
      label: innerChild.name
    })) || []
  })) || []
}));

代码清理

createSubChildren = (children = []) => {
  return (
    (children &&
      children.map(child => ({
        value: child.id,
        label: child.name
      }))) ||
    []
  );
};

createChildren = (children = []) => {
  return (
    children &&
    children.map(child => ({
      value: child.id,
      label: child.name,
      children: this.createSubChildren(child.categorySubChildResponses)
    }))
  ) || [];
};

const options = this.state.allCategory.map(category => ({
  value: category.id,
  label: category.name,
  children: this.createChildren(category.categorySubResponses)
}));

演示


推荐阅读