首页 > 解决方案 > 使用 if else reactjs 渲染按钮

问题描述

我今天在玩 React js,但一度卡住了。基本上,我想渲染一个基于 if-else 运算符的按钮。但是,当值变为等于 0 时,第一部分(显示“错误”)正在工作,而第二部分(渲染按钮)则没有。

import React, { Component } from 'react';
class Items extends Component {
    
    state = { 
count: 0

     }
    
addItem=()=>
{
    this.setState({addition: this.state.count++})
    
}
removeItem=()=>
{
 let error;
    if(this.state.count===0)
    {
        this.setState({param: this.state.count="Error "});
       error= <button>Ooops <button>
        
        
        
    }
    else
    {
        this.setState({subtraction: this.state.count--})

    }
        }
    
       
                
  
    

    render() { 
        return ( 
            
<div>

<text>
Current count: {this.state.count}

</text>
<button onClick={this.addItem}>Increment</button>
<button onClick={this.removeItem}>Decrement</button>
<h3>{this.state.count}</h3>








</div>



         );
    }
}
 
export default Items;

我知道这个问题可能听起来很愚蠢,但任何帮助将不胜感激!

标签: javascriptreactjs

解决方案


试试下面的代码:

import React, { Component } from 'react';

class Items extends Component {

  state = {
    count: 0
  }

  addItem = () => {
    // ++ operator mutates the state object which should not be used!
    // The key should be 'count' instead of 'addition'.
    this.setState({ count: this.state.count + 1 })
  }

  removeItem = () => {
    // -- operator mutates the state object which should not be used!
    // The key should be 'count' instead of 'addition'.
    this.setState({ count: this.state.count - 1 })
  }

  render() {
    // The error message can be conditionally rendered based on the state value inside the render function.
    // Remember to close the button tag, you forgot to use the leading slash.
    return (
      <div>

        <text>
          Current count: {this.state.count}
        </text>
        <button onClick={this.addItem}>Increment</button>
        <button onClick={this.removeItem}>Decrement</button>
        <h3>{this.state.count}</h3>

        {this.state.count === 0 ? (<button>Ooops </button>) : ''}

      </div>
    );
  }
}

export default Items;

推荐阅读