3

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

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

添加一个在其组件中使用箭头函数的依赖项作为来自 react-native-material-kit ( https://github.com/xinthink/react-native-material-kit ) 的 MKIconToggle 不会被正确转译并且这个参考丢失/错误。

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

_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 引用等于窗口,由于 _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% 重现这种行为,我也见过它与其他依赖关系,但它似乎来来去去,尽管一旦发生它通常不会再消失。

4

1 回答 1

0

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

于 2016-05-26T08:59:53.330 回答