代码之家  ›  专栏  ›  技术社区  ›  Eduard

React refs:无法读取null的属性“focus”

  •  0
  • Eduard  · 技术社区  · 7 年前

    https://codesandbox.io/s/14mq9969j3

    我的目标是能够专注于内心的投入 GrandChildInput 通过单击div in ChildInput this.childRef.current null ,直到我通过单击输入来手动关注输入之前,它一直是这样。在那之后 current 正在分配。

    您可以在控制台中跟踪此转换。这个 此.childRef.current 日志只出现一次,但通过单击手动聚焦输入后,其值会发生变化。

    • 反应16.4.2

    但是当涉及到在CodeSandbox中使用通过上面的链接安装在项目中的版本时,出于某种原因,即使关注非样式化的输入组件也不起作用。

    当我点击时,如何使应用程序集中在输入组件上 div 孩子的投入?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Shubham Khatri    7 年前

    当您尝试使用ref将onClick处理程序分配给div时,它将尝试立即从ref访问handleFocus,但因为它尚未分配给输入组件。它的值将为null,因此您将得到该错误。

    至于要打印的值,在控制台中是正确的,这与控制台如何计算值有关。 This answer

    因此,为了解决您的问题,您需要做的是调用handleFocus函数,方法是将其包装到另一个函数中,使其仅在单击时进行求值

    <div
        onClick={() => this.childRef.current.handleFocus()}
        style={{ border: "1px solid black", padding: 5 }}
      >
        click me
        <GrandChildInput
          type="text"
          disabled
          focused
          length={5}
          ref={this.childRef}
        />
      </div>
    

    如果你想知道为什么你的方法不起作用。这是因为没有什么导致render方法被再次调用,所以在ref被分配并且可用之后,正确的函数被分配给onClick。

    Working CodeSandbox

        2
  •  0
  •   Eduard    7 年前

    加起来 @ShubhamKhatri styled-component 以及 4 .

    Uncaught TypeError: _this.childRef.current.handleFocus is not a function .

    在这种情况下,重命名 ref 属性 innerRef 这种方式:

    <div
    onClick={() => this.childRef.current.handleFocus()}
    style={{ border: "1px solid black", padding: 5 }}
    >
      click me
      <StyledGrandChildInput
        type="text"
        disabled
        focused
        length={5}
        innerRef={this.childRef} // change
      />
    </div>