如何在单击按钮时显示可折叠文本块

How to show a block of collapsible text on click of button

我正在尝试实现一个可折叠组件。我将其设计为在单击按钮时会出现一个动态文本块。我制作了一个功能组件并使用 class 中的标签。组件的名称是 CustomAccordion.jsx 并在 Container.jsx

中使用此组件

我已经尝试为 onClick 事件创建一个按钮和一个函数。

部分CustonAccordion.jsx

const handleToggle = () : string =>{
    let content = this.nextElementSibling;

    if (content.style.maxHeight){
        content.style.maxHeight = null;

    }else{
        content.style.maxHeight = content.scrollHeight +'px';
    }
}

export default function CustomAccordion(props: PropType): React.Component<*> {
    const { title, children } = props

    return(
        <div>
        <AccordionButton onClick={() => this.handleToggle()}>{title}</AccordionButton>
        <AccordionContent>
        <p>{children}
        </p>
        </AccordionContent>
        </div>
    )
}

调用部分Container.jsx

<CustomAccordion title = {this.props.name}>
    <p>This is the text passed to component.</p>
</CustomAccordion> 
<br />

这并没有显示展开的文本,似乎点击事件没有正常工作。我是react新手,猜测语法可能不正确。

在 React 中,你通常应该尽量避免直接触摸 DOM,除非你真的必须这样做。

此外,您错误地访问了 handleToggle 函数。它应该是 onClick={() => handleToggle()} 因为 this 在你的情况下是 window/null 所以它没有 handleToggle 方法。

相反,您可以使用有状态 class 组件来实现相同的目的。

export default class CustomAccordion extends React.Component {
  state = {show: false};
  toggle = () => this.setState({show: !this.state.show});
  render() {
    const {title, children} = this.props;
    const {show} = this.state;
    return (
      <div>
        <AccordionButton onClick={this.toggle}>{title}</AccordionButton>
        {show && (
          <AccordionContent>
            <p>{children}</p>
          </AccordionContent>
        )}
      </div>
    )
  }
}

如果你想要某种动画,你可以根据show状态而不是adding/removing元素设置不同的class名称。