【发布时间】:2016-09-23 19:01:06
【问题描述】:
在我的项目中,this 在升级到 React Native 26 后使用箭头函数时不再绑定。
如果我在下面的示例中不使用.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时也运行:
- watchman watch-del-all
- npm start --reset-cache
- 我还编辑文件(添加注释)以确保它重新编译。
旁注:有趣的是即使使用.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"
]
}
【问题讨论】:
-
您有我们可以查看的示例 sn-p 代码吗?例如,您能否在babeljs.io/repl 上重现该问题?
-
已添加示例。我很确定我的 package.json 或 .babelrc 中的某些东西会导致问题。
-
添加 .babelrc 肯定是这个问题,但不知道解决方案是什么。
标签: react-native babeljs relayjs