无法读取未定义的属性(读取'header')

4

我正在尝试使用这个stackoverflow帖子中的自定义折叠面板,但当我包含它时,出现了无法读取未定义属性(正在读取'header')的问题。我不知道出了什么问题,因为它在Codepen上完全正常运行。
以下是代码:
基本上是一样的,只是我添加了一些图标。

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>
  );
};

这里是我使用Collapse的地方:

<div className={styles.telegramLinks}>
     <AntCollapse header="test">
        <h1>test</h1>
     </AntCollapse>
</div>
2个回答

1
在CustomCollapse的声明中:
const CustomCollapse = ({props}) => {
 // ...
};

应该是

const CustomCollapse = (props) => {
 // ...
 // use `props.header`
};

否则的话,就好像你在组件上寻找一个名为 props 的属性,也就是说,一个名为 props 的 props。
或者你可以这样声明:
const CustomCollapse = ({ header }) => {
 // ...
 // use `header` directly instead of `props.header` 
};

1
可以了,谢谢!我写了 ({props}) 是因为有一条红线提示 必须使用解构 props 赋值,所以我加了花括号来消除错误,没想到这会导致它不起作用。 - Leo

0

我相信如果你想以这种方式获取props,你需要使用:

const CustomCollapse = (props) => {

替代

const CustomCollapse = ({props}) => {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接