Mat*_*cci 6 reactjs next.js react-hooks
我试图在外部组件上使用 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)}
/>
Run Code Online (Sandbox Code Playgroud)
完整代码:https : //codesandbox.io/s/objective-benz-qh4ec?file=/ pages/index.js: 63-73
fcF*_*cFn 14
您需要将组件包装在自定义组件中。
包装你的Editor组件:
import React from "react";
import Editor from "react-markdown-editor-lite";
export default function WrappedEditor({ editorRef, ...props }) {
return <Editor {...props} ref={editorRef} />;
}
Run Code Online (Sandbox Code Playgroud)
然后动态导入:
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)}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用自定义 prop 方法而不使用forwardRef.
Editor完全按照前面的示例包装您的组件:
import React from "react";
import Editor from "react-markdown-editor-lite";
export default function WrappedEditor({ editorRef, ...props }) {
return <Editor {...props} ref={editorRef} />;
}
Run Code Online (Sandbox Code Playgroud)
将自定义 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)}
/>
);
}
Run Code Online (Sandbox Code Playgroud)