在Reaction中使用ForwardRef时,我不能声明自定义属性;这可以用<MyInput ref={ref}></MyInput>,但我不能像这样向它添加自定义属性:

<MyInput someval={someval} ref={ref}></MyInput>

错误是

"某些值不能分配给内部属性(&A;RefAttributes)"

//this is the parent component
export const Recognizer: React.FunctionComponent = () => {

  const ref = useRef(null);

  function handleClick() {
    ref.current.focus();
  }

  const [someval, setSomeVal] = useState(1);


return ( <div>
      <MyInput  someval={someval} ref={ref}></MyInput>
      <Button onClick={handleClick}>test</Button>)
};

// child component 

const MyInput = forwardRef(function MyInput(prop, ref) {
  const inputRef = useRef(null);

  useImperativeHandle(
    ref,
    () => {
      return {
        focus() {
          console.log("calling focus");
          inputRef.current.focus();
        },
        scrollIntoView() {
          console.log("calling scroll");
          inputRef.current.scrollIntoView();
        },
      };
    },
    []
  );

  return <div ref={inputRef} />;
});

export default MyInput;

推荐答案

我猜你用的是TypeScrip,这个错误是来自TypeScrip Linter.要解决这个问题,您需要为MyInput定义props 类型,下面是一个示例.

type MyInputProps = {
  someval: number
}
const MyInput = forwardRef<YourRefType, MyInputProps>(function MyInput(
  prop,
  ref
) {
  const inputRef = useRef(null)

  useImperativeHandle(
    ref,
    () => {
      if (!inputRef.current) return

      return {
        focus() {
          console.log('calling focus')
          inputRef.current.focus()
        },
        scrollIntoView() {
          console.log('calling scroll')
          inputRef.current.scrollIntoView()
        },
      }
    },
    []
  )

  return <div ref={inputRef} />
})

你还需要定义YourRefType.

Reactjs相关问答推荐

react应用程序中的字体不适用于.scss扩展名

sourceBuffer. appendBuffer成功,但h5视频播放器卡住了

通过单击具有此值的按钮将值添加到数组对象键

如何在MUI X数据网格列中显示IMG?

ReactJs;Reaction-Hook-Form:仅当 Select 了特定 Select 列表选项时才显示文本输入

梅X折线图无响应

在数组对象内的数组上进行映射

在Reaction中管理多个状态

安装使用环境的BIT组件的依赖项

定位数组中的一项(React、useState)

Mui / Material UI 5:如何从 StaticTimePicker 中删除打开下一个视图/打开上一个视图按钮?

无法使用 MongoDB Atlas 和 Next.js 删除正确的帖子

BrowserRouter改变了URL但没有链接到页面

将外部 JavaScript 导入 React(通过文件)

从 API 中提取映射数组后出现重复元素

React 中的 Slide API Mui 在开始而不是结束时触发侦听器

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

使用 useRef(uuid()) 的目的是什么?

如何不旋转 mui 自动完成弹出图标?

在状态中存储多个选定的选项