簡體   English   中英

邏輯語句中的 react-native state 變量不起作用

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

我只想在計數小於 4 時才呈現單擊按鈕,否則打印“helo there”。 變量 count 是一個 state 變量,初始值為 0; 隨着按鈕被點擊而增加。 但是 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>);
    }
  }
}

由於您的count在您的 state 內,您應該將 if 語句更改為:

if(this.state.count<4){

您正在使用 this.props.count,而不是 props.count,在 if 語句中使用this.state.count<4 props 用於從父組件獲取屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM