You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将使用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:

  • useState becomes class-level state (initialized in the constructor)
  • useRef becomes React.createRef() (assigned as a class property)
  • Event handlers need proper this binding (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 useState calls, we use a single state object in the constructor to hold both active and height values. We update them together with this.setState().
  • Ref Handling: this.contentRef replaces the content ref from your original component. We access the DOM element with this.contentRef.current, just like content.current in the Hooks version.
  • Event Handler: Using an arrow function for toggleAccordion eliminates the need to manually bind this in the constructor, keeping the code cleaner.
  • Render Logic: The JSX is almost identical to your original, but we pull values from this.state and this.props instead of the Hook variables.

内容的提问来源于stack exchange,提问作者Muzamil Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 07:27:45