使用自定义Antd Collapse组件报Cannot read properties of undefined (reading 'header')错误
报错解决方案
报错原因
- 自定义组件
CustomCollapse的入参解构错误:你写的({props})是从传入的属性对象中提取名为props的属性,而非获取整个属性对象,导致内部使用的props变量为undefined,读取props.header时触发报错 - 组件调用逻辑错误:你调用时使用的是原生
AntCollapse组件,而非自己封装的CustomCollapse组件,封装逻辑完全没有生效
修复后代码
自定义组件实现
const CustomCollapse = (props) => { const [disabled, setDisabled] = useState(true); return ( <StyledCollapse onChange={() => setDisabled(prev => !prev)}> <AntCollapse.Panel header={props.header} key="1" showArrow={false} bordered={false} extra={ <span> <span style={{ color: "#0076de", float: "right" }}> {disabled ? <div id="themeBox"><p>+10</p></div> : <img src={arrowDownIcon} alt="" style={{objectFit:'contain'}} />} </span> </span> } > {props.children} </AntCollapse.Panel> </StyledCollapse> ); };
组件调用代码
<div className={styles.telegramLinks}> <CustomCollapse header="test"> <h1>test</h1> </CustomCollapse> </div>
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

