Реактивный реф. Ток равен NULL - PullRequest
0 голосов
/ 24 ноября 2018

У меня есть этот код, взятый из официальных документов React Ref

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

1 Ответ

0 голосов
/ 24 ноября 2018

Код в порядке, так как его точно такой же пример присутствует в реактивных документах.Проблема в том, что ваша react-dom версия старше.React.createRef() API был представлен в React 16.3 (для использования React.createRef() все связанные с react пакеты должны быть 16,3+).Проверьте эту ссылку в документах.

Ваши зависимости:

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

Проблема исправлена ​​после обновления react-dom до 16.6.3

Проверьте это:https://codesandbox.io/s/n7ozx9kr0p

...