【问题标题】:`forwardRef` error when dynamically importing a module in Next.js在 Next.js 中动态导入模块时出现“forwardRef”错误
【发布时间】:2020-12-07 16:11:31
【问题描述】:

我正在尝试在外部组件上使用 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

更多信息:https://github.com/vercel/next.js/issues/4957

【问题讨论】:

    标签: reactjs react-hooks next.js


    【解决方案1】:

    您需要将组件包装在自定义组件中。

    使用 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)}
        />
      );
    }
    

    CodeSandbox

    您也可以使用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)}
        />
      );
    }
    

    CodeSandbox

    【讨论】:

    • 但是为什么呢?有什么解释为什么在这种情况下需要不同的方法?
    猜你喜欢
    • 2021-10-24
    • 2022-11-30
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2021-05-20
    相关资源
    最近更新 更多