简体   繁体   English

逻辑语句中的 react-native state 变量不起作用

[英]react-native state variable in logical statement not working

I want to render click button only when the count is less than 4, otherwise print "helo there".我只想在计数小于 4 时才呈现单击按钮,否则打印“helo there”。 The variable count is a state variable with value zero initially;变量 count 是一个 state 变量,初始值为 0; which increments as button is clicked.随着按钮被点击而增加。 But the output is "helo there" only though count is zero.. Why it is so...??但是 output 只是“helo there”,尽管计数为零。为什么会这样......??

import * as React from 'react';
import {Component} from 'react';
import { Text, View, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  render() {

    if(this.props.count<4){
      return (
      <View>
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
      </View>
    );
    }
    else
    {
      return(<View><Text>{this.state.count}</Text></View>);
    }
  }
}

Since your count is inside your state, you should change the if statement to:由于您的count在您的 state 内,您应该将 if 语句更改为:

if(this.state.count<4){

you are using this.props.count, instead of props.count, use this.state.count<4 in if statement.您正在使用 this.props.count,而不是 props.count,在 if 语句中使用this.state.count<4 props are used to get properties from parent component. props 用于从父组件获取属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM