TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

我是 React.js 的新手,刚才我正在学习 React 中 ref 的概念。他们在 V16.3 中有新的 createRef API。我试图像这样从 REACT DOC's 学习这个 -

import React from "react";

export class MyComponent 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();
}

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>
    );
}

}

我遇到了这个错误 -

TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef 不是函数

这是截图-

您似乎没有安装正确版本的 react

这样做:

npm install --save react@16.4.0 react-dom@16.4.0

如果你不能升级你的反应版本,你可以使用旧的字符串引用(https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs

您为 ref 属性设置了字符串:

<input
    type="text"
    ref="textInput" />

并像这样访问它:

this.refs.textInput.focus();

别忘了删除这部分:

this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);