我使用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%重现这种行为,我也看到了它与其他依赖关系,但它似乎来来去去,虽然一旦它发生它通常不会消失了。
答案 0 :(得分: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
我的项目及其所有箭头功能都有效。