如何便捷获取React循环生成按钮的time与disabled属性值?
如何更简便地获取React循环生成按钮的time和disabled属性?
你现在通过嵌套访问props.children的方式太脆弱,一旦DOM结构变动代码就会失效,而且写起来繁琐。给你两个更靠谱的解决思路:
1. 提前抽离按钮数据,实现数据与UI分离(推荐)
你当前是在map里硬写Button的属性,不如先把所有时间插槽的属性整理成一个数据数组,生成UI时基于这个数组循环,要获取属性直接操作数组即可,完全不用碰React元素的props:
// 先定义好所有按钮的属性数据 const timeSlots = [ { time: "8", disabled: false, label: "8:00 AM" }, { time: "9", disabled: false, label: "9:00 AM" }, { time: "10", disabled: false, label: "10:00 AM" } ]; // 基于数据生成UI const dates = days.map(product => <div className='col-sm'> <div className='col-md'> {timeSlots.map(slot => ( <Button key={slot.time} time={slot.time} disabled={slot.disabled} > {slot.label} </Button> ))} </div> </div> ); // 直接遍历数据数组获取属性 timeSlots.forEach(slot => { console.log('time:', slot.time, 'disabled:', slot.disabled); });
这是React的最佳实践,数据驱动UI,后续修改按钮属性、新增时间点只需改动timeSlots数组,不用调整UI代码,彻底避免了解析React元素结构的麻烦。
2. 编写工具函数遍历React元素树提取Button属性
如果无法修改UI生成逻辑,必须从已生成的dates元素中获取属性,可以写个递归函数遍历整个React元素树,自动定位所有Button组件并提取属性:
// 递归遍历React元素,提取所有Button的time和disabled属性 function getButtonProps(element) { const result = []; // 当前元素是Button时提取属性 if (element.type === Button) { result.push({ time: element.props.time, disabled: element.props.disabled }); } // 处理子元素:数组则循环遍历,单个则递归 const children = element.props.children; if (children) { if (Array.isArray(children)) { children.forEach(child => { result.push(...getButtonProps(child)); }); } else { result.push(...getButtonProps(children)); } } return result; } // 使用方式:遍历dates中的每个元素,提取所有Button属性 const allButtonProps = dates.flatMap(item => getButtonProps(item)); allButtonProps.forEach(props => { console.log(props.time, props.disabled); });
这个函数不受DOM嵌套结构影响,只要是Button组件就能被定位,不用手动写children[1].children[0]这种固定路径,容错性更高。
内容的提问来源于stack exchange,提问作者abc903
相关产品推荐
相关产品推荐

