reactjs - 在 Next.js 中动态导入模块时出现“forwardRef”错误
问题描述
我正在尝试在外部组件上使用 forwardRef 但ref.current
不是实际的ref
. 不确定我是否遗漏了什么。
我正在做:
const Editor = dynamic(() => import("react-markdown-editor-lite"), {
ssr: false
});
const ForwardedRefEditor = forwardRef((props, ref) => (
<Editor {...props} ref={ref} />
));
-----
const editorRef = useRef(null);
<ForwardedRefEditor
ref={editorRef}
value={content}
onChange={({ text }) => setContent(text)}
/>
完整代码:https ://codesandbox.io/s/objective-benz-qh4ec?file=/pages/index.js:63-73
解决方案
您需要将组件包装在自定义组件中。
使用 forwardRef:
包装你的Editor
组件:
import React from "react";
import Editor from "react-markdown-editor-lite";
export default function WrappedEditor({ editorRef, ...props }) {
return <Editor {...props} ref={editorRef} />;
}
然后动态导入:
import dynamic from "next/dynamic";
import { useRef, useState, forwardRef } from "react";
const Editor = dynamic(() => import("../WrappedEditor"), {
ssr: false
});
const ForwardRefEditor = forwardRef((props, ref) =>
<Editor {...props} editorRef={ref}/>
)
export default function IndexPage() {
const editorRef = useRef(null);
const [content, setContent] = useState("");
console.log("editorRef", editorRef.current);
return (
<ForwardRefEditor
ref={editorRef}
value={content}
onChange={({ text }) => setContent(text)}
/>
);
}
您也可以使用自定义道具方法而不使用forwardRef
.
自定义道具
Editor
完全按照前面的示例包装您的组件:
import React from "react";
import Editor from "react-markdown-editor-lite";
export default function WrappedEditor({ editorRef, ...props }) {
return <Editor {...props} ref={editorRef} />;
}
将自定义 ref 属性传递给Editor
组件:
import dynamic from "next/dynamic";
import { useRef, useState } from "react";
const Editor = dynamic(() => import("../WrappedEditor"), {
ssr: false
});
export default function IndexPage() {
const editorRef = useRef(null);
const [content, setContent] = useState("");
console.log("editorRef", editorRef.current);
return (
<Editor
editorRef={editorRef}
value={content}
onChange={({ text }) => setContent(text)}
/>
);
}
推荐阅读
- django - 如何为每个复选框 CheckBoxSelectMultiple 添加额外的属性?
- bash - 有没有办法避免 awk 中出现“字符串中的换行符”错误?
- javascript - 如何在表格中将分数划分为答案?
- node.js - Firebase 函数:只会变得未定义
- node.js - 如何使用 Google Datastore 查询“对象数组”(多个过滤器)
- html - html a href 语法错误。意外的 '$row' (T_VARIABLE),需要 ',' 或 ';'
- razor - 在另一个程序集中更新视图时,页面未反映我的更改
- python - Raspberry Pi 启动后不启动 python 脚本等待输入
- python - 包括 base.html 中的登录表单
- angular - Angular httpClient order of server responses