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

为何无法在JS中创建自定义useEditor Hook?编译报错求助

解决React自定义Hook返回组件时的渲染错误

错误原因

你遇到的报错是因为直接将useEditor返回的对象当作React子元素渲染了。React只能渲染合法的子元素(比如React组件实例、字符串、数字等),而你返回的{Editor, handleChange}是普通JavaScript对象,无法被React识别为可渲染节点。

解决方案

使用useEditor时,需先解构出返回对象中的Editor组件,再以组件形式(<Editor />)渲染,而非直接渲染整个返回对象。

正确使用示例

import useEditor from './useEditor';

function YourParentComponent() {
  // 调用Hook并解构出组件和方法
  const { Editor, handleChange } = useEditor();

  // 父组件中处理编辑器内容的示例逻辑
  const handleSubmit = () => {
    console.log('执行提交操作');
  };

  return (
    <div className="editor-container">
      {/* 渲染解构出的Editor组件 */}
      <Editor />
      <button onClick={handleSubmit}>提交内容</button>
    </div>
  );
}

可选优化:暴露编辑器状态

如果需要在父组件中直接获取编辑器内容,可修改useEditor,将editorHtml加入返回对象:

// 修改useEditor的return部分
return {
  Editor,
  handleChange,
  editorHtml // 新增,让父组件能拿到当前编辑器的HTML内容
};

父组件中即可直接使用该状态:

const { Editor, editorHtml } = useEditor();

const handleSubmit = () => {
  console.log('当前编辑器内容:', editorHtml);
  // 提交到后端等后续操作
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:35:16