React使用createRef API报错:TypeError: React.createRef is not a function
解决React中
createRef is not a function的报错 嘿,我懂你现在的困扰!你写的代码逻辑完全没问题,但这个报错的根源其实是你的React版本低于16.3.0——毕竟createRef确实是React 16.3版本才新增的API,版本不够的话自然识别不了这个方法。
下面给你两个可行的解决方案:
方案一:升级React版本到16.3.0及以上
直接通过包管理工具升级React和React-dom,执行对应的命令就行:
- 使用npm:
npm install react@^16.3.0 react-dom@^16.3.0 --save - 使用yarn:
yarn add react@^16.3.0 react-dom@^16.3.0
升级完成后,你原来写的代码就能正常运行了。
方案二:使用旧版的回调Ref写法(不升级版本)
如果暂时不想升级React版本,你可以用React 16.3之前推荐的回调Ref方式来实现同样的功能,修改后的代码如下:
import React from "react"; export class MyComponent extends React.Component { constructor(props) { super(props); this.textInput = null; this.focusTextInput = this.focusTextInput.bind(this); } focusTextInput() { // 直接调用DOM元素的focus方法 if (this.textInput) { this.textInput.focus(); } } render() { return ( <div> {/* 用回调函数把DOM元素赋值给textInput */} <input type="text" ref={(input) => { this.textInput = input; }} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
这种写法和createRef的效果是一样的,都能获取到对应的DOM元素并调用它的方法。
内容的提问来源于stack exchange,提问作者hardy
相关产品推荐
相关产品推荐

