【问题标题】:React - Passing focus functions to child components using refsReact - 使用 refs 将焦点函数传递给子组件
【发布时间】: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


【解决方案1】:

在 React 中我们必须使用 React.forwardRef

在下面的示例中,FancyButton 使用 React.forwardRef 获取传递给它的 ref,然后将其转发给它渲染的 DOM 按钮:

const FancyButton = React.forwardRef((props, ref) => (  <button ref={ref} className="FancyButton">    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

【讨论】:

  • 当我尝试这样做时,我得到“无法读取 null 的属性(读取'焦点')”
  • 更新了我的答案,我使用了不同的方法
  • 这与原始代码和功能完全不同。我不认为我可以通过这种方式尝试 focus()。
猜你喜欢
  • 2021-08-20
  • 2021-12-02
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
  • 2018-07-02
  • 2017-03-03
相关资源
最近更新 更多