简体   繁体   English

为什么我不能在点击时切换此按钮

[英]Why can't I toggle this button on click

I am trying to achieve a behavior on click.我正在尝试实现点击行为。 What I want is to have the button show “Click to close” when clicked, and then once you click again - revert back to its initial state (showing 'Easy Riddles').我想要的是让按钮在单击时显示“单击以关闭”,然后再次单击 - 恢复到其初始 state(显示“简单谜语”)。

Here is a snippet of my code:这是我的代码片段:

import React, { useState } from "react";
import { Accordion, Card, Button, Container, Row, Col } from "react-bootstrap";

const Riddles = (props) => {
  const levelStatus = {
    easy: "Easy Riddles",
    medium: "Intermediate Riddles",
    hard: "Hard Riddles",
  };

  const collapseButton = "Click to close";

  const [close, setClose] = useState({
    easy: false,
    medium: false,
    hard: false,
  });

  // Handle click
  const handleClick = (e) => {
    setClose({
      close.easy: true
    });
  };

  return (
    <>
      <div className="riddlesection">
        <Container>
          <Row>
            <Col className="riddlegrid" xs={12} sm={12} md={4}>
              <Accordion>
                <Card id="easy">
                  <Card.Header>
                    <Accordion.Toggle
                      id="easy"
                      onClick={handleClick}
                      value="Easy Riddles"
                      as={Button}
                      variant="link"
                      eventKey="0"
                    >
                      {close.easy ? levelStatus.easy : collapseButton}
                    </Accordion.Toggle>
                  </Card.Header>
                  <Accordion.Collapse eventKey="0">
                    <Card.Body>
                      <Row>
                        <Col xs={6} sm={6} md={6}>
                          Countdown
                        </Col>
                        <Col className="resetlink" xs={6} sm={6} md={6}>
                          Switch
                        </Col>
                      </Row>
                      <div>Hello! I'm the body</div>
                    </Card.Body>
                  </Accordion.Collapse>
                </Card>
              </Accordion>
            </Col>
          </Row>
        </Container>
      </div>
    </>
  );
};

What can I do to achieve differently the behavior that I want?我可以做些什么来以不同的方式实现我想要的行为?

you need to update the state as below您需要更新 state 如下

const handleClick = (e) => {     
   setClose(prevCloseState => {
      ...prevCloseState,
       easy: true
    })    
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM