将react-native与react-relay一起使用时,引用节点模块的箭头函数中的自动绑定被破坏

2024-03-13

我正在使用react-native和react-relay,因此我有以下 .babelrc 文件:

{
  "sourceMaps": "both",
  "presets": [
    "./plugins/babelRelayPlugin",
    "react-native"
  ],
  "passPerPreset": true
}

添加一个依赖项,在其组件中使用箭头函数作为react-native-material-kit中的MKIconToggle(https://github.com/xinthink/react-native-material-kit https://github.com/xinthink/react-native-material-kit) 未正确转译,并且 this 引用丢失/错误。

最终导致错误的原始代码如下所示:

_onLayout = (evt) => {
    this._onLayoutChange(evt.nativeEvent.layout);

    if (this.props.onLayout) {
      this.props.onLayout(evt);
    }
  };

错误情况下受影响的代码片段:

d(55, function(global, require, module, exports) {var _this = this,
    _jsxFileName = '.../node_modules/react-native-material-kit/lib/mdl/Ripple.js';
var Ripple = function (_Component) {
  babelHelpers.inherits(Ripple, _Component);

  function Ripple(props) {
    babelHelpers.classCallCheck(this, Ripple);

    var _this2 = babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(Ripple).call(this, props));

    _this2._onLayout = function (evt) {
      _this._onLayoutChange(evt.nativeEvent.layout);

      if (_this.props.onLayout) {
        _this.props.onLayout(evt);
      }
    };

_this 引用等于 window,由于 _this 的使用,创建并使用了 _this2,但 _this 仍在箭头函数(_onLayout)中使用

当我删除 babelrc 文件并且默认运行时,我得到以下转译的 JS 并且它可以工作:

__d(921, function(global, require, module, exports) {var jsxFileName='...../node_modules/react-native-material-kit/lib/mdl/Ripple.js';

Component=React.Component;var Animated=React.Animated;var View=React.View;var PropTypes=React.PropTypes;var Platform=React.Platform;var Ripple=function(_Component){
babelHelpers.inherits(Ripple,_Component);
function Ripple(props){babelHelpers.classCallCheck(this,Ripple);
var _this=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(Ripple).call(this, props));
_this._onLayout=function(evt){
_this._onLayoutChange(evt.nativeEvent.layout);

if(_this.props.onLayout){
_this.props.onLayout(evt);}};_this.

我不太确定导致问题的原因,我可以通过绑定构造函数中的函数来修复它,但我不想直接更改依赖项中的代码。 我已经尝试过向 babel conf 添加各种预设:es2015、stage-0、babel-preset-react-native-stage-0 和其他一些预设,但都没有成功。

有趣的是,这种行为不会发生在所有依赖项中,也不会发生在我自己的代码中,如果我只编写一个带有箭头函数的单个组件并使用 babelrc ,它仍然可以工作。

我无法 100% 重现此行为,我也曾在其他依赖项中看到过它,但它似乎来来去去,尽管一旦发生它通常就不会消失了。


babel-preset-react-native-stage-0 最终做到了。 不确定缓存中或其他地方还剩下什么,但在清除所有内容后: watchman watch-del-all rm -rf $TMPDIR/react-* rm -rf node_modules npm install npm start --reset-cache 我的项目及其所有箭头功能都可以工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将react-native与react-relay一起使用时,引用节点模块的箭头函数中的自动绑定被破坏 的相关文章

随机推荐