如何将含多个draft-js编辑器的React类组件转换为函数组件
React类组件转函数组件实现(多draft-js编辑器数组)
下面是可直接运行的转换后代码,同时修复了原类组件中状态更新未做数组不可变处理的潜在问题:
import React, { useState } from "react"; import { EditorState } from "draft-js"; import { Editor } from "react-draft-wysiwyg"; import { stateFromHTML } from "draft-js-import-html"; import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css"; export default function App() { // 初始化编辑器状态数组,逻辑对齐原类组件构造函数 const [editorStates, setEditorStates] = useState(() => { const contents = [ { text: "Sample text", HTML: "<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text</strong></span></p>" }, { text: "Sample text2", HTML: "<p style='text-align: center;'><span style='font-size:3em;'><strong>Sample text2</strong></span></p>" } ]; return contents.map((element) => EditorState.createWithContent(stateFromHTML(element.HTML)) ); }); return ( <> {editorStates.map((editorState, index) => ( <Editor defaultEditorState={editorState} onEditorStateChange={(newState) => { setEditorStates(prev => { const updated = [...prev]; updated[index] = newState; return updated; }); }} key={index} /> ))} </> ); }
转换说明
- 用
useState替代类组件的this.state/this.setState,初始状态放在useState的惰性初始化回调中,避免组件每次重渲染都重复执行初始EditorState生成逻辑,减少性能损耗 - 状态更新时通过浅拷贝生成新的数组副本,符合React不可变状态要求,避免原类组件写法中数组引用不变导致的重渲染异常问题
- TypeScript适配只需要补充状态类型即可,核心逻辑无需修改:
// TS版本状态定义示例 const [editorStates, setEditorStates] = useState<EditorState[]>(() => { // 初始化逻辑和JS版本完全一致 }) - 原代码中未使用的
ContentState、htmlToDraft导入可以移除,减少无效依赖
内容的提问来源于stack exchange,提问作者Miangel
相关产品推荐
相关产品推荐

