简体   繁体   English

在 React 中将 function 作为 Prop 传递的正确方法是什么

[英]What is the correct way to pass a function as a Prop in React

There are a few questions with similar wording but none that helps me.有一些措辞相似的问题,但没有一个对我有帮助。

I have a parent component, that wants to pass a function to a child component through Props, and the child component will execute the function within its logic.我有一个父组件,它想通过 Props 将 function 传递给子组件,子组件将在其逻辑内执行 function。 However, ESLint is returning me the error "JSX props should not use functions react/jsx-no-bind ".但是,ESLint 向我返回错误“JSX 道具不应使用函数react/jsx-no-bind ”。 I understand that this is inefficient because the function will be re-created everytime the component re-renders.我知道这是低效的,因为每次重新渲染组件时都会重新创建 function。 What would be the correct way to do this?这样做的正确方法是什么?

Parent Component父组件

function App() {
  const [recipes, setRecipes] = useState(sampleRecipes);

  function handleRecipeAdd() {
    const newRecipe = // some logic to create newRecipe here
    setRecipes([...recipes, newRecipe]);
    
  }

  return <RecipeList recipes={recipes} handleRecipeAdd={handleRecipeAdd} />;
}

Child Component子组件

interface Props {
  handleRecipeAdd: () => void;
}

export default function RecipeList(props: Props) {
  const { handleRecipeAdd } = props;
  return (
        <button onClick={handleRecipeAdd}>
          Add Recipe
        </button>
  );
}

Note that this is not the exact code for both components, it has been simplified to remove irrelevant code.请注意,这不是两个组件的确切代码,它已被简化以删除不相关的代码。

Huge thanks to Robin Zigmond for pointing me to the correct place to look at, this has been resolved with the useCallback hook.非常感谢 Robin Zigmond 为我指出了正确的查看位置,这已通过 useCallback 挂钩解决。 For anyone who is interested, here's what the updated code looks like:对于任何感兴趣的人,更新后的代码如下所示:

Parent Component父组件

function App() {
  const [recipes, setRecipes] = useState(sampleRecipes);

  const handleRecipeAdd = useCallback(() => {
    const newRecipe = // some logic to create newRecipe here
    setRecipes([...recipes, newRecipe]);
  }, [recipes]);

  return <RecipeList recipes={recipes} handleRecipeAdd={handleRecipeAdd} />;
}

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

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