将状态值设置为单击按钮的值
Set value of state to clicked button's value
我正在尝试将我的 state
设置为用户按下的 2 个按钮中的哪一个。
const [pizzaSize, setPizzaSize] = useState(null);
const changePizza = (e) => {
setPizzaSize(e.target.value)
}
<button type="button" onClick={() => changePizza()}>Medium</button>
这是抛出以下错误TypeError: Cannot read property 'target' of undefined
我知道我没有正确执行此操作,但我无法弄清楚如何将状态设置为单击按钮的值。
我的完整代码是 here 以备不时之需。
谢谢你的时间。
您必须将值 属性 赋给现在设置为未定义的按钮,并将事件传递给处理程序 Function
<button type="button" value = "Medium" onClick={(e) => changePizza(e)}>Medium</button>
您甚至可以直接传递函数,事件参数将自动传递给 changePizza
<button type="button" value = "Medium" onClick={changePizza}>Medium</button>
或者您可以直接这样做
<button type="button" value = "Medium" onClick={(e) =>setPizzaSize(e.target.value)}>Medium</button>
我正在尝试将我的 state
设置为用户按下的 2 个按钮中的哪一个。
const [pizzaSize, setPizzaSize] = useState(null);
const changePizza = (e) => {
setPizzaSize(e.target.value)
}
<button type="button" onClick={() => changePizza()}>Medium</button>
这是抛出以下错误TypeError: Cannot read property 'target' of undefined
我知道我没有正确执行此操作,但我无法弄清楚如何将状态设置为单击按钮的值。
我的完整代码是 here 以备不时之需。
谢谢你的时间。
您必须将值 属性 赋给现在设置为未定义的按钮,并将事件传递给处理程序 Function
<button type="button" value = "Medium" onClick={(e) => changePizza(e)}>Medium</button>
您甚至可以直接传递函数,事件参数将自动传递给 changePizza
<button type="button" value = "Medium" onClick={changePizza}>Medium</button>
或者您可以直接这样做
<button type="button" value = "Medium" onClick={(e) =>setPizzaSize(e.target.value)}>Medium</button>