【问题标题】:How to show a block of collapsible text on click of button如何在单击按钮时显示一块可折叠的文本
【发布时间】:2019-05-24 21:49:51
【问题描述】:

我正在尝试实现一个可折叠组件。我已经设计了它,例如,单击一个按钮,就会出现一个动态文本块。我制作了一个功能组件并在类中使用标签。组件的名称是 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 />

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

【问题讨论】:

    标签: reactjs button collapsable


    【解决方案1】:

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

    你也错误地访问了handleToggle 函数。它应该是onClick={() =&gt; handleToggle()},因为在你的情况下thiswindow/null,所以它没有handleToggle 方法。

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

    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状态设置不同的className,而不是添加/删除元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 2012-11-30
      • 2023-03-05
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多