React类组件转函数组件:this.chart与useRef问题及示例需求
问题解答
核心问题说明
this.chart的处理方式:类组件里的this.chart是用来持久化存储OrgChart实例的,在函数组件中可以通过useRef钩子实现相同效果——useRef的current属性能保存跨组件渲染周期的可变值,不会随重渲染重置,和类组件实例属性的作用完全一致。- 用
useRef替代createRef是否正确:完全正确。createRef每次组件渲染都会生成新的引用对象,而useRef在组件整个生命周期内保持同一个引用,更适合存储这类需要持久化的实例。
完整转换示例
import React, { useRef, useEffect, memo } from 'react'; import OrgChart from '@balkangraph/orgchart.js'; const Chart = memo((props) => { // 存储DOM元素的引用 const divRef = useRef(null); // 存储OrgChart实例的引用 const chartRef = useRef(null); useEffect(() => { // 组件挂载后初始化OrgChart if (divRef.current) { const chart = new OrgChart(divRef.current, { nodes: props.nodes, nodeBinding: { field_0: 'name', img_0: 'img', }, }); // 绑定事件 chart.on('init', () => { console.log('init'); }); chart.on('click', () => { console.log('click'); }); // 将实例存入ref chartRef.current = chart; } // 可选:组件卸载时清理实例(如果OrgChart提供销毁方法) return () => { if (chartRef.current) { // 若OrgChart有destroy或类似方法,可在此调用 // chartRef.current.destroy(); } }; }, []); // 空依赖数组确保只执行一次,对应componentDidMount return <div id="tree" ref={divRef}></div>; }); export default Chart;
关键转换细节
- 替代
shouldComponentUpdate:原类组件中shouldComponentUpdate返回false,用React.memo包裹函数组件能实现相同效果——浅比较props,当props未变化时阻止组件重渲染。 - 实例持久化:
chartRef专门用于存储OrgChart实例,后续如果需要调用实例的方法(比如更新节点),直接通过chartRef.current访问即可。 - 生命周期对应:空依赖的
useEffect等同于componentDidMount,返回的清理函数等同于componentWillUnmount。
内容的提问来源于stack exchange,提问作者Trispo
相关产品推荐
相关产品推荐

