【发布时间】:2022-01-01 13:13:43
【问题描述】:
在我的父组件构造函数(基于类)中,我使用以下方法为输入字段添加了一个引用:
this.usernameRef = React.createRef();
这在父组件中工作得很好。例如,以下工作正常:
const username = this.usernameRef.current.value; // this works
我将 .focus() 对 ref 的调用传递给一个子组件,如下所示:
<ChildComponent
onClick={() => this.usernameRef.current.focus()}
/>
在我的子组件中,它通过 onClick 事件被调用:
<a href="#" onClick={onClick} />
当应用程序运行时,当我点击该链接时,我收到以下错误:
e.usernameRef.current.focus is not a function
我应该以不同的方式解决这个问题吗?
不管怎样,子组件是基于函数的。
谢谢
【问题讨论】:
-
您向我们展示的代码与您收到的错误之间有问题:
this.usernameRef.current.focus()或e.usernameRef.current.focus()?
标签: reactjs react-ref react-class-based-component