我无法正确输入。如果我设置 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/