You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中基于JSON数据联动填充分类与子分类下拉选项?

实现逻辑

  • 导入分类JSON数据,兼容不同的子分类字段名
  • 用两个状态分别管理选中的父分类、子分类列表
  • 父分类选中变化时,实时过滤匹配对应的子分类,重置子分类选中值
  • 无子分类的分类选中后,子分类下拉框自动禁用

完整代码

// 首先导入分类数据,你需要把JSON文件放到项目对应路径
import categoriesData from './categories.json'
import { useState } from 'react'
// 导入ChakraUI需要的组件
import { Box, FormControl, FormLabel, Input, Select, NumberInput, NumberInputField, NumberInputStepper, NumberIncrementStepper, NumberDecrementStepper } from '@chakra-ui/react'

export default function AddProductForm() {
  // 状态管理:选中的父分类slug、子分类列表、选中的子分类slug
  const [selectedCategorySlug, setSelectedCategorySlug] = useState('')
  const [subCategories, setSubCategories] = useState([])
  const [selectedSubCategorySlug, setSelectedSubCategorySlug] = useState('')

  // 父分类切换时的处理逻辑
  const handleCategoryChange = (e) => {
    const currentSlug = e.target.value
    setSelectedCategorySlug(currentSlug)
    // 重置子分类选中值
    setSelectedSubCategorySlug('')

    // 匹配当前选中的父分类
    const matchedCategory = categoriesData.categories.find(item => item.category_slug === currentSlug)
    if (!matchedCategory) {
      setSubCategories([])
      return
    }
    // 兼容子分类字段名不一致的问题:有的是child_categories,有的是child_cat
    const children = matchedCategory.child_categories || matchedCategory.child_cat || []
    setSubCategories(children)
  }

  return (
    <Box display='flex' justifyContent='center' alignItems='center'>
      <Box
        w={[300, 400, 600]}
        border='1px'
        boxShadow='md'
        p={5}
        rounded='md'
        bg='white'
        borderColor='gray.400'
        mx='auto'
      >
        <FormControl id='product' isRequired>
          <FormLabel>商品名称</FormLabel>
          <Input type='text' />
          <FormLabel>分类</FormLabel>   
          <Select value={selectedCategorySlug} onChange={handleCategoryChange} placeholder='请选择分类'>
            {
              categoriesData.categories.map(category => (
                <option key={category.id} value={category.category_slug}>
                  {category.name}
                </option>
              ))
            }
          </Select>
          <FormLabel>子分类</FormLabel>
          <Select 
            value={selectedSubCategorySlug} 
            onChange={(e) => setSelectedSubCategorySlug(e.target.value)} 
            placeholder={subCategories.length ? '请选择子分类' : '当前分类无可用子分类'}
            isDisabled={subCategories.length === 0}
          >
            {
              subCategories.map(sub => (
                <option key={sub.id} value={sub.category_slug}>
                  {sub.name}
                </option>
              ))
            }
          </Select>
          <FormLabel>商品描述</FormLabel>
          <Input type='text' />
          <FormLabel>商品图片</FormLabel>
          <Input type='text' />
          <FormLabel>原价</FormLabel>
          <Input type='number' />
          <FormLabel>售价</FormLabel>
          <Input type='number' />
          <FormLabel>库存数量</FormLabel>
          <NumberInput max={5} min={1}>
            <NumberInputField />
            <NumberInputStepper>
              <NumberIncrementStepper />
              <NumberDecrementStepper />
            </NumberInputStepper>
          </NumberInput>
        </FormControl>
      </Box>
    </Box>
  );
}

注意事项

  • 你需要调整categories.json的导入路径,和你项目里的实际存放位置对应
  • 分类数据里的子分类字段名不统一的问题,建议你后续可以统一修改JSON的字段,去掉兼容逻辑
  • 如果需要提交表单,直接取selectedCategorySlug和selectedSubCategorySlug两个状态的值即可

内容的提问来源于stack exchange,提问作者tanjim anim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:24:06