javascript - 使用 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;
我知道这个问题可能听起来很愚蠢,但任何帮助将不胜感激!
解决方案
试试下面的代码:
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;
推荐阅读
- angular - 类型'可观察的
' 不可分配给类型 'Observable ' - python - 从元组列表中返回有组织的列表
- vba - 将分组图像复制为图片并通过vba将其裁剪为ppt
- python - 熊猫在列名中添加可选后缀作为函数中的参数
- javascript - 无法抓取 Javascript 网站 - API 调用/XHR 请求
- vue.js - 在 Vue js 中强制方法调用后如何从父级获取更新的道具?
- python - 为什么导入在这个 ROS python 脚本中有效
- set - 如何从 cplex 的集合中声明一个子集?
- mongodb - $regex 和 $text 一起在 $or 中
- css - 有 a 类而不是 b 类并且是第 n 个孩子