在我的项目中,在升级到ReactiveNative26之后,当使用箭头函数时,this不再被绑定。
如果在下面的示例中不使用.babelrc,它将与箭头函数一起工作。添加.babelrc时,箭头函数不再工作。
.babelrc
{ "passPerPreset": true, "presets": [ {"plugins":["../schema/babelRelayPlugin"]}, "react-native", ] }
我也试过:
{ "passPerPreset": true, "presets": [ {"plugins":["../schema/babelRelayPlugin"]}, "react-native-stage-0", ] }和
{ "passPerPreset": true, "presets": [ {"plugins":["../schema/babelRelayPlugin"]}, "react-native", {"plugins":["transform-es2015-arrow-functions"]}, ] }
这个错误
class NoArrow extends Component {
constructor(){
super();
this.state={x:0};
}
inc = ()=>{
this.setState({x:this.state.x+1});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome} onPress={this.inc}>
Welcome to React Native! {this.state.x}
</Text>
</View>
);
}
}

这行得通
class NoArrow extends Component {
constructor(){
super();
this.state={x:0};
this.inc=this.inc.bind(this);
}
inc(){
this.setState({x:this.state.x+1});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome} onPress={this.inc}>
Welcome to React Native! {this.state.x}
</Text>
</View>
);
}
}添加/删除.babelrc时,还运行:
附带注意:有趣的是,即使在.babelrc中,这也是有效的。
class NoArrow extends Component {
constructor(){
super();
this.state={x:0};
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome} onPress={()=> this.setState({x:this.state.x+1})}>
Welcome to React Native! {this.state.x}
</Text>
</View>
);
}
}更新1
在$TMPDIR内部删除缓存的文件;它有一个哈希名称,类似于11acb28f1c8d3c6313ca5f8ccba3c158
使用react-native-stage-0可能已经修复了箭头函数问题,但现在Relay.QL已不能正确编译。
{
"passPerPreset": true,
"presets": [
{"plugins":["../schema/babelRelayPlugin"]},
"react-native-stage-0"
]
}

发布于 2016-05-27 03:18:02
我有这个问题,但我很肯定它早于RN 0.24。你有什么版本的babel-core/babel-cli?我本来希望T7191能解决这个问题,但事实并非如此。
我最后做的是使用巴贝尔继电器插件装载机。我不再使用passPerPreset了,它一直在可靠地工作,尽管我并不完全理解它是如何工作的。
下面是我的.babelrc现在的样子:
{
"presets": [
"react-native"
],
"plugins": [
"babel-relay-plugin-loader"
],
"env": {
"web": {
"presets": ["es2015", "stage-0", "react"],
"plugins": ["babel-relay-plugin-loader"]
}
}
}发布于 2016-05-26 08:55:53
不确定这是否真的与26有关,我在25岁时也有同样的问题。看我这里的帖子:当使用react-本机和react中继时,引用节点模块箭头函数中的自绑定中断
对我来说,这个问题不是持久的,经过一段时间的修补之后,它就消失了。从表面上看,反应-本土化-0是为我做的。在清除缓存时,您唯一没有做的就是像这样清除$TMPDIR:rm -rf $TMPDIR/react-*
我试着用一个示例项目来重现我的问题,但是没有,我也会尝试rm -rf node_modules,只是为了确定一下。
https://stackoverflow.com/questions/37449580
复制相似问题