如何将使用React Hooks的Accordion函数组件改写为类组件?
Got it, let's walk through converting this Hooks-based Accordion component to a class component step by step. I'll break down each part so you can see how Hooks map to class-based React features.
Converting the Hooks-based Accordion to a Class Component
First, let's map your original Hooks to class-based React concepts:
useStatebecomes class-levelstate(initialized in the constructor)useRefbecomesReact.createRef()(assigned as a class property)- Event handlers need proper
thisbinding (we'll use arrow functions for simplicity here)
Here's the fully converted class component:
import React from "react"; class Accordion extends React.Component { constructor(props) { super(props); // Initialize state equivalent to your two useState Hooks this.state = { active: "", height: "0px" }; // Create ref equivalent to the useRef hook this.contentRef = React.createRef(); } // Arrow function ensures `this` refers to the class instance toggleAccordion = () => { const { active } = this.state; // Toggle the active class state const newActiveState = active === "" ? "active" : "non-active"; // Calculate content height based on current state const newHeight = active === "active" ? "0px" : `${this.contentRef.current.scrollHeight}px`; // Update state with new values this.setState({ active: newActiveState, height: newHeight }); }; render() { const { active, height } = this.state; const { title, content } = this.props; return ( <div className="accordion__section"> <button className={`accordion ${active}`} onClick={this.toggleAccordion} > <div className="accordion__title" dangerouslySetInnerHTML={{ __html: title }} /> </button> <div ref={this.contentRef} style={{ maxHeight: height }} className="accordion__content" > <div className="accordion__text" dangerouslySetInnerHTML={{ __html: content }} /> </div> </div> ); } } export default Accordion;
Key Details to Note:
- State Management: Instead of separate
useStatecalls, we use a singlestateobject in the constructor to hold bothactiveandheightvalues. We update them together withthis.setState(). - Ref Handling:
this.contentRefreplaces thecontentref from your original component. We access the DOM element withthis.contentRef.current, just likecontent.currentin the Hooks version. - Event Handler: Using an arrow function for
toggleAccordioneliminates the need to manually bindthisin the constructor, keeping the code cleaner. - Render Logic: The JSX is almost identical to your original, but we pull values from
this.stateandthis.propsinstead of the Hook variables.
内容的提问来源于stack exchange,提问作者Muzamil Hussain
相关产品推荐
相关产品推荐

