javascript - 在反应jsx中有条件地呈现className
问题描述
var array = [
['2','35'],
['80','30'],
['300','25']
]
所以这是数组的简化版本,我从 api 调用中得到什么。每个子数组的第一个值是数量,第二个值是价格。下面是我的简化状态
this.state = {quantity:''}
在 jsx 内部,我想做的是根据状态的数量值有条件地渲染一个名为selected的类名。每当状态量发生变化时。所选课程也应相应更改。下面是我的 jsx
{array.map((price, index, arr) => {
if (index < arr.length -1) {
if (parseInt(arr[index+1][0]) > parseInt(this.state.quantity) && parseInt(this.state.quantity) >= parseInt(price[0])){
return (
<div className='price-box selected'>
<h3 className='price'>Tk {price[1]}</h3>
<p className='quantity'>{price[0]} or more</p>
</div>
);
} else {
return (
<div className='price-box'>
<h3 className='price'>Tk {price[1]}</h3>
<p className='quantity'>{price[0]} or more</p>
</div>
);
}
} else {
if (parseInt(this.state.quantity) >= parseInt(price[0])) {
return (
<div className='price-box selected'>
<h3 className='price'>Tk {price[1]}</h3>
<p className='quantity'>{price[0]} or more</p>
</div>
);
} else {
return (
<div className='price-box'>
<h3 className='price'>Tk {price[1]}</h3>
<p className='quantity'>{price[0]} or more</p>
</div>
);
}
}
})}
这里一切正常(除了数量 0 和 1 之外,所有条件都按预期评估为 false。所以没有为单个 div 分配选定的类)。我 100% 确定有一种更短更好的方法。
解决方案
也许像这样的东西就是你要找的东西?
class Quantity extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: "2"
};
}
render() {
const array = [["2", "35"], ["80", "30"], ["300", "25"], ["2"], ["", "3"]]; // With some errors
return (
<div>
<h1>Hello</h1>
{array.map((row) => {
const condition = this.state.quantity === row[0]; // Create your condition
if (row && row[0] && row[1])
return (
<div className={`price-box ${condition && "selected"}`}> // Called template literal, you can simply include selected if your condition is true
<h3>Quantity {row[0]}</h3>
<p>Price {row[1]}</p>
</div>
);
else return <div>Data error</div>;
})}
</div>
);
}
}
推荐阅读
- bash - 解析 iw wlan0 站转储输出
- android - 当我运行我的程序时,Android Studio 找不到设备
- javascript - 使用 Javascript 在无限循环中发送 1 个 GET 请求和 2 个 POST 请求
- python - 使用 opencv-python 跟踪一个或多个任意的、以前未知的对象
- haskell - Haskell Guards 涉及布尔运算和 Do
- python - 为什么我定义它时没有定义它?(名称错误)
- node.js - 在另一个函数中等待一个承诺
- json - 您好大师,有人可以告诉我我的 JSON 语法字符串有什么问题吗?
- python - sklearn lasso 会自动并行运行吗?
- typescript - 如何在 Typescript 中扩展/覆盖导出的类型