React基于JSON数据实现列表点击联动展示对应值的代码如何编写?
React动态切换组件实现代码
核心实现逻辑是通过状态记录当前选中的列表项索引,替换原代码中固定写死的[0]下标,点击列表项时更新状态即可实现数据联动切换。
import { useState } from 'react' import Bar from './Bar' // 按你实际文件路径引入Bar组件 function YourComponent() { // 定义状态记录当前选中的functionalInfo项索引,默认选中第0项 const [selectedIndex, setSelectedIndex] = useState(0) // 注意核对字段名拼写:你提供的JSON里是functionalInfo、igredientsInfo,原代码里写的functionalsInfo、ingredientsInfo,按实际返回的字段调整 const currentFunctionalItem = ProductDetail?.chart?.functionalInfo?.[selectedIndex] const currentIngredients = currentFunctionalItem?.materialsInfo?.[0]?.igredientsInfo?.[0] // 提取当前选中项的对应字段 const barLabels = currentIngredients ? [currentIngredients.ingredientDisplayText] : [] const chartStatus = currentIngredients?.chartStatus || '' const displayNum = currentIngredients?.ingredientDisplayText || '' return ( <div> {/* 列表渲染 */} <ul> {ProductDetail?.chart?.functionalInfo?.length ? ( ProductDetail.chart.functionalInfo.map((info, index) => ( <li key={info.id || index} onClick={() => setSelectedIndex(index)} style={{ cursor: 'pointer' }} > {info.seedShapeDisplayText} </li> )) ) : ( <li>There is not</li> )} </ul> {/* 下方展示区域 */} {currentIngredients && ( <div> <div>Hi Number {chartStatus}, Bar : {displayNum}</div> <Bar labels={barLabels} /> </div> )} </div> ) }
调整说明
- 新增状态
selectedIndex记录当前选中的列表项下标,默认值为0对应第一个选项 - 给每个
<li>绑定点击事件,点击时更新selectedIndex为当前项的下标 - 所有取值逻辑不再固定取数组第0项,改为取
[selectedIndex]对应下标的数据,实现切换效果 - 如果你的
igredientsInfo数组有多个值需要批量提取,修改barLabels的取值逻辑为数组map即可
内容的提问来源于stack exchange,提问作者ssksksks
相关产品推荐
相关产品推荐

