简体   繁体   English

React 回调函数不起作用如何解决?

[英]React callback function does not work how to fix it?

On one of my react Components I need to use a callback function.在我的一个反应组件上,我需要使用回调函数。 The the construction of my site is like this:我的网站建设是这样的:

<Mainview >
<Header />
<Main />
<Footer />
</Mainview>

In one of my Main Component I used this:在我的一个主要组件中,我使用了这个:

  const Produkt = (produkt, { zumWarenkorbHinzufuegen }) => {

    return (
    <main>
    // ...
    
    <input 
       type="button" 
       value="In den Warenkorb" 
       id="Knopfwarenkorb1" 
       onClick={() => { zumWarenkorbHinzufuegen(produkt.id) }} />
 
    // ...
  
 </main>

In the main view I used this :在主视图中我使用了这个:

    <Route path="/bambus-zahnbuerste" component={() => <Produkt id={produkt[0].id}
                name={produkt[0].name}
                bild={produkt[0].bild}
                preis={produkt[0].preis}
                zumWarenkorbHinzufuegen={zumwarenkorb} />} />

The function "zumwarenkorb" is also defined in the <Mainview /> <Mainview />中也定义了函数“zumwarenkorb”

So when I click the button on my <Produkt /> Component I get the following error:因此,当我单击<Produkt />组件上的按钮时,出现以下错误:

TypeError: zumWarenkorbHinzufuegen is not a function. (In 'zumWarenkorbHinzufuegen(produkt.id)', 'zumWarenkorbHinzufuegen' is undefined)

Your component's props are passed through the first argument of the Produkt function, or in your case the produkt argument.您的组件的道具通过 Produkt 函数的第一个参数传递,或者在您的情况下是produkt参数。 To access the value of the zumWarenkorbHinzufuegen prop, you have to unpack it from produkt in the body of your function:要访问zumWarenkorbHinzufuegen的值,您必须在函数体中从produkt中解压它:

const { zumWarenkorbHinzufuegen } = produkt;

You can destructure props in Produkt component to get produkt id and zumWarenkorbHinzufuegen function.您可以在 Produkt 组件中解构 props 以获取 produkt id 和 zumWarenkorbHinzufuegen 函数。

const Produkt = ({id,  zumWarenkorbHinzufuegen }) => {}

or you can keep the props and use like或者你可以保留道具并使用

const Produkt = (props) => {
  ...
  <input type="button" 
         value="In den Warenkorb" 
         id="Knopfwarenkorb1" 
         onClick={() => { props.zumWarenkorbHinzufuegen(props.id) }} 
   />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM