【问题标题】:react-hook-form and typescript - property 'inputRef' does not exist on type DetailedHTMLPropsreact-hook-form 和 typescript - 类型DetailedHTMLProps 上不存在属性'inputRef'
【发布时间】:2021-06-17 15:03:21
【问题描述】:

这是我的 react-hook - 控制器

      <Controller
        control={control}
        name={name}
        defaultValue={defaultValue}
        rules={validate}
        ref={register({
          validate
        })}
        render={props => (
          <input
            name={props.name}
            value={props.value}
            ref={props.ref}
            type={'text'}
            placeholder={label}
            aria-label={label}
            onChange={handleChange}
            data-error={errorText !== '' && errorText}
          />
        )}
      />

问题是 ref 不起作用。它需要是 inputRef - 由 react-hook-form 示例确定。 如果我使用 inputRef,我会收到打字稿错误:

“DetailedHTMLProps”类型上不存在属性“inputRef”

如果我尝试将该属性添加到 index.d.ts 文件中,它会破坏我所有其他声明的模块..

declare module 'react' {
  import React from 'react';

  interface HTMLInputAttributes<T> extends React.HTMLAttributes<T> {
    // extends React's HTMLAttributes
    inputRef?: any;
  }
}

declare module '*.svg' {
  const content: any;
  export const ReactComponent: any;
  export default content;
}

【问题讨论】:

    标签: typescript react-hook-form react-forwardref


    【解决方案1】:

    我已将 ref 放在 Controller 上,而它本应在输入本身中。 修复:

          <Controller
            control={control}
            name={name}
            render={props => (
              <input
                name={props.name}
                defaultValue={defaultValue}
                ref={register({
                  validate
                })}
                type={'text'}
                placeholder={label}
                aria-label={label}
                onChange={handleChange}
                data-error={errorText !== '' && errorText}
              />
            )}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-21
      • 2018-02-23
      • 2019-11-26
      • 2018-07-31
      • 2020-02-18
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      相关资源
      最近更新 更多