【问题标题】:How to fix a collapse button in react?如何修复反应中的折叠按钮?
【发布时间】:2021-02-19 01:11:52
【问题描述】:

我想定义一个加号按钮,当您单击它展开您的内容并将加号转换为减号。 您能帮我修复以下课程中的折叠按钮吗:

import React from "react";


class FaqButton extends React.Component {
  constructor() {
    super();
    this.state = {
      button: <span>&#43;</span>,
      flag: 0,
      classN: "button-plus",
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    if (this.state.flag === 0) {
      this.setState({
        button: <span>&#8211;</span>,
        flag: 1,
        classN: "selected",
      });
    } else {
      this.setState({
        button: <span>&#43;</span>,
        flag: 0,
        classN: "button-plus",
      });
    }
  }
  render() {
    return (
      <div>
        <button className={this.state.classN} onClick={this.handleClick}>
          {this.state.button}
        </button>

        
      </div>
    );
  }
}

export default FaqButton;

【问题讨论】:

    标签: reactjs collapse


    【解决方案1】:

    只保留flag 状态,基于此您可以更改模板。 您还可以根据state 中的flag 属性显示内容,如下所示,

    import React from "react";
    import "./styles.css";
    
    export default class App extends React.Component {
      constructor() {
        super();
        this.state = {
          flag: 0
        };
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState({
          flag: this.state.flag === 0 ? 1 : 0
        });
      }
      render() {
        return (
          <div>
            <button
              className={this.state.flag === 1 ? "selected" : "button-plus"}
              onClick={this.handleClick}
            >
              {this.state.flag === 1 ? <span>&#8211;</span> : <span>&#43;</span>}
            </button>
            {this.state.flag === 1 && (
              <div style={{ border: "2px solid green" }}>
                Lorem Ipsum is simply dummy text of the printing and typesetting
                industry. Lorem Ipsum has been the industry's standard dummy text
                ever since the 1500s, when an unknown printer took a galley of type
                and scrambled it to make a type specimen book. It has survived not
                only five centuries, but also the leap into electronic typesetting,
                remaining essentially unchanged. It was popularised in the 1960s
                with the release of Letraset sheets containing Lorem Ipsum passages,
                and more recently with desktop publishing software like Aldus
                PageMaker including versions of Lorem Ipsum.
              </div>
            )}
          </div>
        );
      }
    }
    

    演示 - https://codesandbox.io/s/sad-einstein-thokp?file=/src/App.js:95-1627

    【讨论】:

    • 一点建议,你也可以用flag来切换按钮和类
    猜你喜欢
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2020-09-28
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多