gpt4 book ai didi

javascript - 有条件的 onclick 函数在没有点击的情况下触发?

转载 作者:行者123 更新时间:2023-12-05 09:36:22 25 4
gpt4 key购买 nike

我已经设置了一个条件元素,点击我在 React 中制作的按钮。但是默认属性在不单击按钮的情况下运行 onload 我该如何解决这个问题?

按钮看起来像这样:

<p onClick={Butter + Milk + Bread + Soup + Cheese > 0 ? props.next_ClickHandler : alert('Please Input some food!')}>Buy Now!</p>

我希望这样,如果值加起来大于 0,则传递 Prop ,但如果不播放警报,为什么它不能按预期工作?

编辑完整代码:

import React, { useState, useEffect, useContext } from "react";
import Data from '../shoppingData/Ingredients';
import { quantitiesContext } from '../shoppingData/Quantities';

const ShoppingPageOne = (props) => {

//element displays
const [pageone_show, setPageone_show] = useState("pageOne");

//stores quantities of items as JSON objects
const [Quantities, setQuantities] = useContext(quantitiesContext);

const quantities = useContext(quantitiesContext);

const Bread = quantities[0].Bread.quantities;
const Milk = quantities[0].Milk.quantities;
const Cheese = quantities[0].Cheese.quantities;
const Soup = quantities[0].Soup.quantities;
const Butter = quantities[0].Butter.quantities;

useEffect(() => {
//sets info text using Json
if (props.showOne) {
setPageone_show("pageOne");
} else {
setPageone_show("pageOne hide");
}
}, [props.showOne]);


return (
<div className={"Shopping_Content " + pageone_show}>


<div className="Shopping_input_aligner">
<div className='Shopping_input_container'>
{Data.map((Ingredients) => {

//updates Quanties Hook
const handleChange = (event) => {

setQuantities({
...Quantities,
[Ingredients.Name]: {
...(Quantities[Ingredients.Name] ?? {}),
quantities: event.target.value
}
});
};

return (<div className={"Shopping_input " + Ingredients.Name} key={Ingredients.Name}>
<p>{Ingredients.Name} £{Ingredients.Price}</p>
<input onChange={handleChange.bind(this)} min="0" placeholder="Input food quantity" type="number"></input>
</div>)
})}
</div>

<div className='Discount_list'>
<h3>Discounts:</h3>
<li>Buy one cheese get one free!</li>
<li>Buy a Soup get a half price bread!</li>
<li>A third off butter!</li>
</div>
</div>
<div className="Shopping_Buttons">
<p onClick={() => {Butter + Milk + Bread + Soup + Cheese > 0 ? props.next_ClickHandler : alert('Please Input some food!')}} >Buy Now!</p>
</div>

</div>
);
};

export default ShoppingPageOne;

最佳答案

如果您使用的是 React Hooks,您可以使用类似这样的代码来获得更清晰的代码

const [ingredientsGreaterThanZero, setIngredientsGreaterThanZero] = useState(false);

useEffect(() => {
if (butter + milk + bread + soup + cheese > 0) {
setIngredientsGreaterThanZero(true)
} else {
setIngredientsGreaterThanZero(false)
}
}, [butter, milk, bread, soup, cheese]);

...

{ingredientsGreaterThanZero ?
<p onClick={props.next_ClickHandler}>Buy Now!</p> :
<p onClick={() => alert('Please Input some food!')}>Buy Now!</p>
}

关于javascript - 有条件的 onclick 函数在没有点击的情况下触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65182756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com