【问题标题】:React ref current is NULL反应参考电流为 NULL
【发布时间】:2019-04-26 21:25:22
【问题描述】:

我的代码取自官方 React 参考文档

import React from "react";
import { render } from "react-dom";

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    // this.textInput.current.focus();
    console.log(this.textInput);
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />

        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
const A = () => {
  return <div>
    <CustomTextInput />
  </div>
}
render(<div><A/></div>, document.getElementById("root"));

当调用 focusTextInput 时,它会记录“current: null”。 这是演示:https://codesandbox.io/s/wo6qjk9xk7

【问题讨论】:

    标签: reactjs ref


    【解决方案1】:

    代码很好,因为它是 react 文档中的 exact same example。问题是您的 react-dom 版本较旧。 React.createRef() API 是在 React 16.3 中引入的(所有与 react 相关的包都应该是 16.3+ 才能使用 React.createRef())。检查文档中的this reference

    你的依赖:

     "dependencies": {
        "react": "16.6.3",
        "react-dom": "16.2.0"
      },
    

    react-dom 更新到 16.6.3 后问题已修复

    检查这个:https://codesandbox.io/s/n7ozx9kr0p

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 2020-10-18
      • 2019-04-24
      • 2020-07-10
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多