React select下拉框设置超250最大价格选项语法不生效如何解决
问题解决方法
错误原因
你写的setMaxPrice(>250)语法不生效,是因为>250不是合法的JavaScript值,变量只能存储数值、字符串等具体类型,不能直接把比较运算符作为值的一部分存储。
实现方案
我们可以用JS内置的Infinity(无穷大)来代表“无上限”的最高价格,之后在渲染和业务逻辑判断时做特殊处理即可:
- 价格赋值逻辑修改:把case4的maxPrice设置为
Infinity - 显示逻辑修改:渲染最高价格时,判断如果是
Infinity就显示为>250,否则显示原数值
修改后的完整代码
import { useState } from "react"; import "./styles.css"; export default function App() { const [minPrice, setMinPrice] = useState(0); const [maxPrice, setMaxPrice] = useState(50); const handlePrice = (value) => { switch (value) { case "1": setMinPrice(0); setMaxPrice(50); break; case "2": setMinPrice(50); setMaxPrice(100); break; case "3": setMinPrice(100); setMaxPrice(250); break; case "4": setMinPrice(250); setMaxPrice(Infinity); // 用无穷大代表无上限 break; default: setMinPrice(0); setMaxPrice(50); break; } }; return ( <div className="App"> <select className="custom-select" id="priceGroup" onChange={(event) => handlePrice(event.target.value)} > <option value="1">Under $50</option> <option value="2">$50 to $100</option> <option value="3">$100 to $250</option> <option value="4">Over $250</option> </select> <div>Your min price is {minPrice}</div> {/* 特殊处理最高价格的显示 */} <div>Your max price is {maxPrice === Infinity ? '>250' : maxPrice}</div> </div> ); }
后续业务逻辑适配
如果你后续需要用这两个价格值过滤商品,判断逻辑可以这么写:
const isMatch = (goodsPrice) => { if (maxPrice === Infinity) { return goodsPrice >= minPrice } return goodsPrice >= minPrice && goodsPrice <= maxPrice }
内容的提问来源于stack exchange,提问作者endlessLearning
相关产品推荐
相关产品推荐

