首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将react-native与react-relay一起使用时,引用的节点模块的箭头函数中的自动绑定中断

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

Stack Overflow用户
提问于 2016-05-19 21:03:21
回答 1查看 104关注 0票数 3

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

代码语言:javascript
复制
{
  "sourceMaps": "both",
  "presets": [
    "./plugins/babelRelayPlugin",
    "react-native"
  ],
  "passPerPreset": true
}

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

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

代码语言:javascript
复制
_onLayout = (evt) => {
    this._onLayoutChange(evt.nativeEvent.layout);

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

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

代码语言:javascript
复制
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,但在箭头函数(_onLayout)中仍使用了_this

当我删除babelrc文件并默认运行时,我得到了以下转换后的JS,并且它工作正常:

代码语言:javascript
复制
__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%重现这种行为,我也在其他依赖项中看到过它,但它似乎来来去去,尽管它一旦发生,通常不会再消失。

EN

回答 1

Stack Overflow用户

发布于 2016-05-26 16:59:53

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37324044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档