Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 条件onclick函数在没有单击的情况下触发?_Javascript_Reactjs_React Hooks_Conditional Statements_React Props - Fatal编程技术网

Javascript 条件onclick函数在没有单击的情况下触发?

Javascript 条件onclick函数在没有单击的情况下触发?,javascript,reactjs,react-hooks,conditional-statements,react-props,Javascript,Reactjs,React Hooks,Conditional Statements,React Props,我在react中单击一个按钮时设置了一个条件元素。但是默认道具运行onload而不单击按钮如何解决此问题 按钮如下所示: <p onClick={Butter + Milk + Bread + Soup + Cheese > 0 ? props.next_ClickHandler : alert('Please Input some food!')}>Buy Now!</p> 0?道具。下一步\u ClickHandler:alert('请输入一些食物!')}>立

我在react中单击一个按钮时设置了一个条件元素。但是默认道具运行onload而不单击按钮如何解决此问题

按钮如下所示:

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

0?道具。下一步\u ClickHandler:alert('请输入一些食物!')}>立即购买

我希望这样,如果值加起来大于0,道具就会被传递,但如果没有播放警报,为什么它不能按预期工作

编辑完整代码:

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;
import React,{useState,useffect,useContext}来自“React”;
从“../shoppingData/Components”导入数据;
从“../shoppingData/Quantilities”导入{quantitiesContext};
const ShoppingPageOne=(道具)=>{
//元素显示
const[pageone_show,setPageone_show]=useState(“pageone”);
//将项目数量存储为JSON对象
常量[数量,设置数量]=使用上下文(数量上下文);
常量数量=useContext(quantitiesContext);
常量面包=数量[0]。面包。数量;
常量牛奶=数量[0]。牛奶。数量;
常量Cheese=数量[0]。Cheese.quantities;
常量汤=数量[0]。汤。数量;
常量黄油=数量[0]。黄油。数量;
useffect(()=>{
//使用Json设置信息文本
如果(道具秀一){
setPageone_show(“pageOne”);
}否则{
设置页面显示(“页面隐藏”);
}
},[props.showOne]);
返回(
{Data.map((成分)=>{
//更新量化挂钩
常量handleChange=(事件)=>{
设定量({
…数量,
[配料.名称]:{
…(数量[成分名称]??{}),
数量:event.target.value
}
});
};
返回(
{配料.名称}{配料.价格}

) })} 折扣:
  • 买一块奶酪送一块
  • 买汤买半价面包
  • 三分之一的黄油
  • {黄油+牛奶+面包+汤+奶酪>0?道具。下一步\u ClickHandler:alert('请输入一些食物!')}>立即购买

    ); }; 导出默认ShoppingPageOne;

    {黄油+牛奶+面包+汤+奶酪>0?道具。下一步\u ClickHandler:alert('请输入一些食物!')}>立即购买


    你能试着用这个吗?

    如果你用的是React钩子,你可以有一个更干净的代码

    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>
    }
    
    const[ingreditensgreaterthanzero,setingreditensgreaterthanzero]=useState(false);
    useffect(()=>{
    如果(黄油+牛奶+面包+汤+奶酪>0){
    SettingCreditsCreaterthanzero(真)
    }否则{
    SettingCreditsCreaterthanzero(假)
    }
    },[黄油、牛奶、面包、汤、奶酪];
    ...
    {IngreditsGreaterthanzero?
    

    立即购买!

    提醒('请输入一些食物!')}>立即购买

    }
    原因

    如果使用
    onClick()
    或任何其他事件处理程序在元素中附加任何事件,
    您不应该像示例中那样添加任何函数调用
    alert()

    因为,在括号中,
    ()
    当组件装入dom时,函数运行

    示例:

    错误的方式

    解决方案
    您必须添加一个空函数并在其中写入代码。如果代码包含函数调用
    (带括号())

    示例:

    警报(“仅在单击时运行”)}>右键


    快乐编码:)

    我们能看更多的代码吗?我认为最好检查一个函数中的条件,该函数在每次您的值更改(使用componentDidUpdate或useEffect)时都会触发,但不幸的是,它甚至无法编译如果next_ClickHandler是一个函数,您应该将其更改为next_ClickHandler()。它应该编译这是伟大的,并修复我的解决方案!我唯一的问题是,我仍然不知道为什么另一个不起作用?这是因为您必须向onClick传递回调,例如:
    onClick={console.log('log')}
    变成
    onClick={()=>console.log('log')}
    //请参阅react-docs:
    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>
    }