javascript - 使用 React.forwardRef 时在 React/TypeScript 中给 ref 什么类型?

标签 javascript reactjs typescript draftjs

我无法正确输入。如果我设置 ref: any,我将转发一个可以正常工作的 ref如下图和ref.current.focus()有效。

function EditorFeat(): JSX.Element {
  const ref = useRef<HTMLElement | null>(null);

   // ...
   return (
    ......
    <Editor state={state} dispatch={dispatch} ref={ref} />
     ....
)
}

export default EditorFeat;

interface IEditor {
  state: AppState;
  dispatch: React.Dispatch<Action>;
}

// change ref:any to correct typings!
function Editor({ state, dispatch }: IEditor, ref: any): JSX.Element {
// ...
  return <DraftJsEditor ref={ref} /> // import from 'draft-js'
}

export default React.forwardRef(Editor);

但一旦我尝试获取 ref正确输入,我总是收到错误!

如果我这样做 function Editor({state, dispatch}: IEditor, ref: HTMLElement): JSX.Element

我得到下一个错误:

  Overload 1 of 2, '(props: Readonly<DraftEditorProps>): DraftEditor', gave the following error.
    Type 'HTMLElement' is not assignable to type 'string | ((instance: DraftEditor | null) => void) | RefObject<DraftEditor> | null | undefined'.
      Type 'HTMLElement' is not assignable to type 'string'.
  Overload 2 of 2, '(props: DraftEditorProps, context?: any): DraftEditor', gave the following error.
    Type 'HTMLElement' is not assignable to type 'string | ((instance: DraftEditor | null) => void) | RefObject<DraftEditor> | null | undefined'.
      Type 'HTMLElement' is not assignable to type 'string'

如果我尝试 React.RefObject<DraftEditor>我得到:

Argument of type '({ state, dispatch }: IEditor, ref: RefObject<DraftEditor>) => Element' is not assignable to parameter of type 'ForwardRefRenderFunction<DraftEditor, IEditor>'.
  Types of parameters 'ref' and 'ref' are incompatible.
    Type '((instance: DraftEditor | null) => void) | MutableRefObject<DraftEditor | null> | null' is not assignable to type 'RefObject<DraftEditor>'.
      Type 'null' is not assignable to type 'RefObject<DraftEditor>'

最佳答案

对于功能组件,这就像一个魅力,即使有点不寻常:

function RichEditor(props: RichEditorProps) {
  const [editor, setEditor] = React.useState<Editor | null>(null);

  React.useEffect(() => {
    editor?.focus() // or anywhere you want to use it
  }, [editor])
    

  return (
    <Editor
      ref={editor => setEditor(editor)}
    />
  )
}

关于javascript - 使用 React.forwardRef 时在 React/TypeScript 中给 ref 什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62868117/

相关文章:

javascript - 将嵌套 JavaScript 循环重构为 CoffeeScript 推导式

javascript - 包含照片幻灯片的 iframe 在 Chrome 上中断

javascript - 有没有一种方法可以比较两个数字中的相应整数而不将它们转换为数组

typescript - 是否可以从对象的联合中获取 key ?

node.js - ElasticSearch typescript 支持

javascript - 如何从 URL 中的哈希中获取搜索查询

javascript - fluent-ffmpeg 将 MKV 转换为 MP4 会出现错误 "Conversion Failed"

javascript - Axios - 如何读取 JSON 响应?

javascript - FlowRouter - 将内容插入 HTML 模板

javascript - "CUSTOM_ELEMENTS_SCHEMA"Angular 2 App 测试错误