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

React 15.4版本不支持createRef运行报错该如何解决?

解决方案

React 15.4 未内置 React.createRef() API,你可以使用旧版支持的回调ref语法替换即可实现完全一致的效果,适配后的代码如下:

import React, { Component } from 'react';
const TrustBox = ({ trustBoxRef }) => (
  <div ref={trustBoxRef} className="trustpilot-widget">
    <a href="https://www.trustpilot.com/review/example.com" target="_blank" rel="noopener noreferrer">
    Trustpilot
    </a>
  </div>
);
class TrustBoxContainer extends Component {
  constructor(props) {
    super(props);
    // 初始化实例属性用于存储DOM节点
    this.trustBoxRef = null;
  }
  
  componentDidMount() {
    if (window.Trustpilot) {
      // 直接读取实例属性即可拿到真实DOM,无需访问.current
      window.Trustpilot.loadFromElement(this.trustBoxRef, true);
    }
  }
  
  render() {
    // 传入回调函数获取DOM节点并赋值给实例属性
    return <TrustBox trustBoxRef={node => this.trustBoxRef = node} />;
  }

}
export default TrustBoxContainer;

核心改动说明

  • 移除 React.createRef() 初始化逻辑,改用普通实例属性存储DOM节点
  • 传递给子组件的ref属性改为回调函数形式,React会在DOM挂载/卸载时自动触发该回调,传入对应DOM节点/Null
  • 使用DOM节点时无需访问.current属性,实例属性本身直接对应真实DOM节点

内容的提问来源于stack exchange,提问作者Ebenezer Anand Arapally

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:45:03