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

如何将React类实现的Bulma可折叠卡片组件改写为Hooks函数组件

实现步骤

我们只需要做三处核心改动就能完成类组件到Hooks函数组件的转换:

  • 用useRef创建DOM引用,替代类组件的字符串ref
  • 用useEffect(空依赖项)模拟componentDidMount生命周期,执行bulmaCollapsible实例挂载逻辑
  • 渲染结构完全复用原有类组件的render内容,关联ref即可

完整可运行代码

import React, { useRef, useEffect } from 'react'
import bulmaCollapsible from '@creativebulma/bulma-collapsible';

function NewCollapsibles () {
    // 创建容器DOM引用
    const collapsiblesRef = useRef(null)

    useEffect(() => {
        // 组件首次挂载完成后初始化bulmaCollapsible实例
        const collapsibles = bulmaCollapsible.attach(".is-collapsible", {
            container: collapsiblesRef.current
        });
        
        // 可选:组件卸载时销毁实例,避免内存泄漏
        return () => {
            collapsibles.forEach(item => item.destroy())
        }
    }, []) // 空依赖确保只执行一次

    return (
        <div ref={collapsiblesRef} id="accordion_first">
            <div className="card">
                <header className="card-header">
                    <p className="card-header-title">
                        Card title
                    </p>
                    <a href="#collapsible-card" data-action="collapse" className="card-header-icon is-hidden-fullscreen" aria-label="more options">
                        <span className="icon">
                            <i className="fas fa-angle-down" aria-hidden="true"></i>
                        </span>
                    </a>
                </header>
                <div id="collapsible-card" className="is-collapsible is-active">
                    <div className="card-content">
                        <p className="title is-4">
                            “There are two hard things in computer science: cache invalidation, naming things, and off-by-one
                            errors.”
                        </p>
                        <p className="subtitle is-5">
                            Jeff Atwood
                        </p>
                    </div>
                    <footer className="card-footer">
                        <p className="card-footer-item">
                            <span>
                                View on <a href="https://twitter.com/codinghorror/status/506010907021828096">Twitter</a>
                            </span>
                        </p>
                        <p className="card-footer-item">
                            <span>
                                Share on <a href="#">Facebook</a>
                            </span>
                        </p>
                    </footer>
                </div>
            </div>
        </div>
    )
}

export default NewCollapsibles 

内容的提问来源于stack exchange,提问作者Mr. Hankey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:06:03