react-native中的“找不到变量:点击”

时间:2019-06-16 05:15:54

标签: javascript react-native object ecmascript-6

以下代码在单击“点击我!”时显示错误。表示找不到变量“ clicks”的按钮,但在状态中正确提及了该变量

import { StyleSheet, Alert, Text, View, TouchableOpacity} from 'react-native';
import { Button } from 'native-base';
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clicks: 0
    };
  }
buttonPressed = () => {
 if(this.state.clicks > 5)
 {
    Alert.alert('Caution!','You have clicked 5 times already!');
    this.setState({clicks: 0});
    this.forceUpdate();
 }
 this.setState({clicks: clicks+1});
}
render() {
    return (
      <View>
        <TouchableOpacity onPress={()=>{this.buttonPressed()}}>
           <Text>Click Me!</Text>
        </TouchableOpacity>
      </View>
)};

3 个答案:

答案 0 :(得分:1)

您没有变量名create-react-app my-react-proj01 --scripts-version=react-scripts@1.1.4 ,应该定义它或使用clicks

更改此

this.state.clicks

对此

this.setState({ clicks: clicks + 1 });

或者对此

this.setState({ clicks: this.state.clicks + 1 });

答案 1 :(得分:1)

{% extends "main/header.html" %} {% block content %} <body> <div class="item-detail"> <h1> Detail </h1> <p>{{ item.name }}</p> </div> </body> {% endblock %} 不是变量-它是clicks的属性。

this.state

答案 2 :(得分:0)

问题在于此行:this.setState({clicks: clicks+1}); 未定义冒号右侧的clicks

您可以做的是使用prevState函数中的setState

this.setState(prevState => ({clicks: prevState.clicks + 1}));