ReactJS中onClick方法无法通过按钮修改变量问题排查
Hey there! I can spot exactly why your "Show Beds" button isn't updating the show variable and toggling the content—let's fix this together.
The Root Problem
You're using a plain JavaScript variable let show = false to track whether the beds should be visible, but plain variables don't trigger React component re-renders. Every time your Hospital component renders (which happens when props change or a parent component re-renders), this variable gets reset to false again. Even when your togglebeds function changes its value, React has no way of knowing it needs to update the UI.
The Solution: Use React's useState Hook
For function components, you need to use React's built-in useState hook to manage state that affects the UI. This hook lets you create reactive state variables—when you update them, React automatically re-renders the component to reflect the new state.
Here's how to modify your code step by step:
- First, import the
useStatehook from React:
import React, { useState } from 'react';
- Replace the plain
showvariable with a state variable:
// Instead of let show = false; const [show, setShow] = useState(false);
showholds the current state valuesetShowis the dedicated function you'll use to update the state
- Update your
togglebedsfunction to usesetShowinstead of directly modifying the variable:
const togglebeds = () => { // Using the functional update form ensures you always use the latest state value setShow(prevShow => !prevShow); }
Full Modified Code
Here's your complete component with all fixes applied:
import React, { useState } from 'react'; import classes from './hospital.module.css'; import {Animated} from "react-animated-css"; const Hospital = props =>{ const [show, setShow] = useState(false); const togglebeds = () => { setShow(prevShow => !prevShow); } return ( <div className={classes.Hospital}> <h1 className={classes.Heading}>{props.name}</h1> <button className={classes.Show} onClick={togglebeds}>Show Beds</button> {show ? ( <Animated animationIn="bounceInLeft" animationOut="fadeOut" isVisible={true}> <p className={classes.Bronze}>Bronze Beds Availability : {props.bed1av}</p> <p className={classes.Price}> Price: {props.bedtype1}</p> <p className={classes.Silver}>Silver Beds Availability : {props.bed2av}</p> <p className={classes.Price}> Price: {props.bedtype2}</p> <p className={classes.Gold}>Gold Beds Availability : {props.bed3av}</p> <p className={classes.Price}> Price: {props.bedtype3}</p> </Animated> ) : null} </div> ); } export default Hospital;
Quick Readability Tip
I wrapped the JSX inside the ternary in parentheses—this is a common React best practice to make complex conditional JSX easier to read, though it's not strictly required.
Now when you click the "Show Beds" button, setShow will update the state, React will re-render the component, and your bed details will toggle correctly!
内容的提问来源于stack exchange,提问作者anita shrivastava

