逻辑语句中的反应本机状态变量不起作用

react-native state variable in logical statement not working

我只想在计数小于4时渲染点击按钮,否则打印"helo there"。变量 count 是一个初始值为零的状态变量;单击按钮时递增。但是输出是 "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>);
    }
  }
}

由于您的 count 在您的州内,您应该将 if 语句更改为:

if(this.state.count<4){

您正在使用 this.props.count, 在 if 语句中使用 this.state.count<4 而不是 props.count。 props 用于从父组件获取属性。