React Native报错“true是保留字”,新手求助双击防重复触发问题
Hey there! Let's work through this issue you're hitting. That "true is a reserved word" error is almost always tied to a small JSX syntax mistake, especially in older React Native versions like 0.50.4. Here's what's going on and how to fix it, plus a solid double-click prevention implementation.
Why the Error Happens
In React Native's JSX, if you want to pass a JavaScript value (like a boolean, variable, or expression) as a component prop, you must wrap it in curly braces {}. If you write something like disabled=true directly, the parser treats true as a string instead of a boolean—and since true is a reserved keyword in JavaScript, it throws that error.
Step-by-Step Fix & Double-Click Implementation
Here's a complete example of a button that prevents duplicate clicks, with the correct syntax to avoid the reserved word error:
import React, { Component } from 'react'; import { TouchableOpacity, Text, StyleSheet } from 'react-native'; class SafeButton extends Component { // Initialize state to track if the button is disabled state = { isButtonDisabled: false, }; handleButtonPress = () => { // Immediately disable the button to block duplicate clicks this.setState({ isButtonDisabled: true }); // Run your actual button logic here (API calls, navigation, etc.) console.log('Button action triggered!'); // Re-enable the button after a delay (adjust time to match your needs) setTimeout(() => { this.setState({ isButtonDisabled: false }); }, 1200); // 1.2 seconds is a safe default for most actions }; render() { const { isButtonDisabled } = this.state; return ( <TouchableOpacity onPress={this.handleButtonPress} // Critical: Wrap the boolean state in curly braces disabled={isButtonDisabled} style={[ styles.button, { backgroundColor: isButtonDisabled ? '#aaa' : '#4CAF50' } ]} > <Text style={styles.buttonText}> {isButtonDisabled ? 'Working...' : 'Tap Me'} </Text> </TouchableOpacity> ); } } const styles = StyleSheet.create({ button: { paddingVertical: 12, paddingHorizontal: 24, borderRadius: 6, margin: 10, }, buttonText: { color: 'white', fontSize: 16, textAlign: 'center', }, }); export default SafeButton;
Key Things to Check in Your Code
- Fix the reserved word error: Replace any prop like
disabled=truewithdisabled={true}(or better, use a state variable likeisButtonDisabledas shown above). - Prevent duplicate clicks: Use component state to toggle the
disabledprop immediately on press, then re-enable it after a delay. This stops users from spamming the button while your action is processing. - Old version quirk: React Native 0.50.4 is pretty outdated, so it's stricter about JSX syntax than newer releases. Always wrap dynamic values (booleans, variables, functions) in
{}when passing them as props.
If you had a different code setup that caused the error, feel free to tweak the example above to match your use case—this pattern should work perfectly for your version.
内容的提问来源于stack exchange,提问作者stevenpcurtis

