如何修复反应中的折叠按钮?

问题描述

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

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>,});
    }
  }
  render() {
    return (
      <div>
        <button className={this.state.classN} onClick={this.handleClick}>
          {this.state.button}
        </button>

        
      </div>
    );
  }
}

export default FaqButton;

解决方法

在该状态下仅保留flag,基于此您可以更改模板。 同样,您也可以根据flag中的state属性显示内容,如下所示,

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