React组件中点击按钮仅触发单个分类评论框显示的问题
The issue here is that you’re using a single boolean state (showing) to control all comment forms—when you toggle this state, every category’s form responds to the same value, so all show or hide together.
To fix this, we need to track which specific category should display its comment form instead of a global toggle. Here’s how to adjust your code:
Step 1: Update the State
Replace the boolean showing with a state value that stores the ID of the category whose form should be visible:
state = { showingCategoryId: null }; // Initialize to null (no form shown by default)
Step 2: Modify the Button Click Handler
Change the onClick logic to toggle visibility for the specific category. We’ll check if the current category’s ID is already active—if so, hide it; otherwise, show it:
<button className="label" onClick={() => this.setState(prevState => ({ showingCategoryId: prevState.showingCategoryId === category._id ? null : category._id }))} > Add Comment </button>
Step 3: Adjust the Form Visibility Condition
Only render the form if the current category’s ID matches the showingCategoryId in state:
{this.state.showingCategoryId === category._id ? ( <div> <form method="post" action="/post/create-posts"> <input type="text" name="body" /> <input type="hidden" name="cat" value={category._id} /> <input type="submit" value="Submit" /> </form> </div> ) : null}
Full Corrected Code Snippet
Here’s your updated component code:
state = { showingCategoryId: null }; renderLists(categories) { if (categories == null) return <div />; return ( <ul className="ul"> {categories.map(category => { return ( <li id={category._id} className="categories" key={category._id}> {category.name} <Posts categ={category._id} /> <button className="label" onClick={() => this.setState(prevState => ({ showingCategoryId: prevState.showingCategoryId === category._id ? null : category._id }))} > Add Comment </button> {this.state.showingCategoryId === category._id ? ( <div> <form method="post" action="/post/create-posts"> <input type="text" name="body" /> <input type="hidden" name="cat" value={category._id} /> <input type="submit" value="Submit" /> </form> </div> ) : null} </li> ); })} </ul> ); } render() { return ( <div> <main className="categories"> {this.renderLists(this.state.category)} </main> </div> ); }
How This Works
- We now track the active category by its ID instead of a global flag.
- Clicking "Add Comment" on a category will either show its form (if hidden) or hide it (if already visible).
- All other categories’ forms remain hidden unless their own button is clicked.
Content of the question originates from Stack Exchange, question author Brez

