我正在尝试在外部组件上使用forwardRef,但是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)}
/>
。不知道我是否想念什么。
我在做
#outer {
display: flex;
justify-content: center;
}
完整代码:https://codesandbox.io/s/objective-benz-qh4ec?file=/pages/index.js:63-73
答案 0 :(得分:1)
您需要将组件包装在自定义组件中。
包装您的 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)}
/>
);
}
您也可以使用 custom prop approach 而不使用 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)}
/>
);
}