简体   繁体   中英

React send function as props

I'm trying to follow a video tutorial, but one part doesn't work for me.

Home.js

import { useState, useEffect } from 'react';
import Bloglist from './components/Bloglist';

const Home = () => {
  const [blogs, setBlogs] = useState([
    { title : 'My new website', body: 'lorem ipsum...', author: 'Mario', id: 1 },
    { title : 'Welcome party', body: 'lorem ipsum...', author: 'Yoshi', id: 2 },
    { title : 'Web dev top tips', body: 'lorem ipsum...', author: 'Mario', id: 3 }
  ]);
  
  const handleDelete = (id) => {
    const newBlogs = blogs.filter(blog => blog.id !== id);
    setBlogs(newBlogs);
  };
  
  useEffect(() => {
    console.log('use effect ran');
  });
  
  return (
    <div className="home">
      <Bloglist blogs={blogs} title="All blogs" handleDelete="{handleDelete}" />
    </div>
  );
};

export default Home;

Bloglist.js

const Bloglist = ({ blogs, title, handleDelete }) => {
  return(
    <div className="blog-list">
      <h2>{ title }</h2>
      {blogs.map((blog) => (
        <div className="blog-preview" key={ blog.id }>
          <h2>{ blog.title }</h2>
          <p>Scritto da { blog.author }</p>
          <button onClick={() => handleDelete(blog.id)}>Delete blog</button>
        </div>
      ))}
    </div>
  );
};

export default Bloglist;

When I click on "Delete blog" the console says: Uncaught TypeError: handleDelete is not a function, why?

If necessary and if possible I can post the link to the video tutorial

Your prop is being passed in as a string ( handleDelete="{handleDelete}" .

Functions passed as props need to references to the function definitions themselves or arrow functions.

For it to work, remove the " so that it's:

<Bloglist blogs={blogs} title="All blogs" handleDelete={handleDelete} />

You're passing a string of {handleDelete} into your Bloglist component instead of the reference to the handleDelete function.

You should replace the following line:

<Bloglist blogs={blogs} title="All blogs" handleDelete="{handleDelete}" />

with

<Bloglist blogs={blogs} title="All blogs" handleDelete={handleDelete} />

In your Home.js file, you have passed the handleDelete function to BlogList in quotations. Try doing it like this:

 <Bloglist blogs={blogs} title="All blogs" handleDelete={handleDelete} />

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