You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-rails项目中出现React.createRef is not a function错误求助

解决React.createRef is not a function错误的方案

嘿,这个问题我之前在项目里也踩过坑!咱们来一步步理清楚:

问题根源

React.createRef()是React 16.3版本才正式推出的API,而你当前通过react-rails gem引入的React版本大概率低于16.3,所以才会抛出这个“不是函数”的错误。

两种解决方案

方案一:升级React和react-rails版本

这是最推荐的长期解决方案,能用上React的新特性:

  1. 打开项目的Gemfile,更新react-rails的版本到支持高版本React的最新版(比如gem 'react-rails', '~> 2.6.1'及以上,具体可根据官方兼容说明调整)
  2. 运行bundle install更新gem
  3. 如果项目用Webpacker管理前端依赖,打开package.json,把react和react-dom的版本更新到^16.3.0或更高,然后运行yarn upgrade react react-dom(或npm update react react-dom)

方案二:使用旧版回调式Ref(无需升级)

如果暂时不想升级版本,可以用React 16.3之前支持的回调式Ref来实现同样功能,修改后的组件代码如下:

class NewItem extends React.Component {
  constructor(props) {
    super(props);
    // 提前绑定this,避免点击时this指向错误
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    var name = this.name.value;
    console.log(name);
  }

  render() {
    return (
      <div>
        <input 
          ref={(inputElement) => this.name = inputElement} 
          placeholder='Enter the name of the item' 
        />
        <button onClick={this.handleClick}>Submit</button>
      </div>
    );
  }
};

这里额外处理了handleClick的this绑定问题——如果不绑定,点击按钮时this会指向window(非严格模式)或undefined(严格模式),导致this.name找不到。你也可以用箭头函数写法简化:handleClick = () => { ... },这样就不用手动绑定了。

小提示

不确定当前React版本的话,可以在浏览器控制台输入React.version查看,能更精准判断问题所在。

内容的提问来源于stack exchange,提问作者Herman Eyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:06:30