React中持续出现‘缺少分号’语法错误,请求排查解决
React语法错误排查与修复
问题根源
你的代码存在几个关键问题,直接引发了语法错误及后续运行问题:
函数组件内的方法定义错误
你采用了类组件的方法声明形式(onPressButton() {}),但App是函数组件,函数内部不能这么定义方法,必须用const/let来声明函数:// 错误写法 onPressButton() { alert('You tapped the button!') } // 正确写法(二选一) const onPressButton = () => { Alert.alert('You tapped the button!'); } // 或者普通函数声明 function onPressButton() { Alert.alert('You tapped the button!'); }函数组件误用
this
函数组件不存在this上下文,因此Button的onPress={this.onPressButton}是错误写法,直接传入函数名即可:<Button onPress={onPressButton} title="Press Me" color="#841584"/>React Native不能直接使用浏览器的
alert
需要导入React Native自带的Alert组件替换原生alert:import { Button, StyleSheet, Text, StatusBar, View, Alert } from 'react-native';
修复后的完整代码
import React from 'react'; import { Button, StyleSheet, Text, StatusBar, View, Alert } from 'react-native'; export default function App() { const onPressButton = () => { Alert.alert('You tapped the button!'); }; return ( <View style={styles.container}> <Text>Open up App.js to start working on your app!</Text> <StatusBar style="auto" /> <Button onPress={onPressButton} title="Press Me" color="#841584"/> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#e0e0e0', alignItems: 'center', justifyContent: 'center', }, });
额外说明
你看到的“缺少分号”报错,本质是函数定义方式错误导致代码解析失败,修复函数声明后该报错会自动消失。函数组件中推荐使用箭头函数,能保证上下文一致性,减少不必要的bug。
内容的提问来源于stack exchange,提问作者devinoff_x
相关产品推荐
相关产品推荐

