TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

╄→尐↘猪︶ㄣ 提交于 2019-12-10 13:29:34

问题


I am new to React.js and just now i was learning the concept of ref in React. They have new createRef API in V16.3. I was trying to learn this from REACT DOC's like this -

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

}

And I was Getting this Error -

TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

Here is the screenshot -


回答1:


You do not seem to have the correct version of react installed

Do this :

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



回答2:


If you can't upgrade your react version, you can use legacy string refs (https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)

You set string for ref attribute:

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

And access it like this:

this.refs.textInput.focus();

And don't forget to remove this part:

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


来源:https://stackoverflow.com/questions/50639842/typeerror-webpack-imported-module-0-react-default-a-createref-is-not-a-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!