简体   繁体   English

React 发送 function 作为道具

[英]React send function as props

I'm trying to follow a video tutorial, but one part doesn't work for me.我正在尝试学习视频教程,但其中一部分对我不起作用。

Home.js主页.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博客列表.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?当我点击“删除博客”时,控制台显示:Uncaught TypeError: handleDelete is not a function,为什么?

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}" .您的道具作为字符串( handleDelete="{handleDelete}" )传入。

Functions passed as props need to references to the function definitions themselves or arrow functions.作为 props 传递的函数需要引用 function 定义本身或箭头函数。

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.您将{handleDelete} string传递给您的Bloglist组件,而不是对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.在您的 Home.js 文件中,您已将句柄删除 function 传递给 BlogList 引用。 Try doing it like this:尝试这样做:

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

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

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