简体   繁体   中英

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 />

So when I click the button on my <Produkt /> Component I get the following error:

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. To access the value of the zumWarenkorbHinzufuegen prop, you have to unpack it from produkt in the body of your function:

const { zumWarenkorbHinzufuegen } = produkt;

You can destructure props in Produkt component to get produkt id and zumWarenkorbHinzufuegen function.

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) }} 
   />
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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