【问题标题】:react-native state variable in logical statement not working逻辑语句中的反应本机状态变量不起作用
【发布时间】:2020-06-07 16:06:37
【问题描述】:

我只想在计数小于 4 时渲染单击按钮,否则打印“helo there”。变量count是初始值为0的状态变量;随着按钮被点击而增加。但是只有当计数为零时,输出才是“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>);
    }
  }
}

【问题讨论】:

    标签: javascript reactjs react-native react-component react-state


    【解决方案1】:

    由于您的count 在您的状态中,您应该将 if 语句更改为:

    if(this.state.count<4){
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 2021-09-04
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多