javascript 类型错误:__WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50639842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function
提问by cooper
I am new to React.js and just now i was learning the concept of refin React. They have new createRef APIin V16.3. I was trying to learn this from REACT DOC'slike this -
我是 React.js 的新手,刚才我正在学习refReact 中的概念。他们在 V16.3 中有新的createRef API。我试图从这样的REACT DOC 中学习这一点 -
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
类型错误:__WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef 不是函数
回答by supra28
You do not seem to have the correct version of react installed
您似乎没有安装正确版本的 react
Do this :
做这个 :
npm install --save [email protected] [email protected]
回答by Gregor A?be
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)
如果您无法升级您的 React 版本,您可以使用旧字符串引用(https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)
You set string for ref attribute:
您为 ref 属性设置字符串:
<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);


