【问题标题】:What is the correct way to pass a function as a Prop in React在 React 中将函数作为 Prop 传递的正确方法是什么
【发布时间】:2022-01-24 16:42:33
【问题描述】:

有几个问题的措辞相似,但没有一个对我有帮助。

我有一个父组件,它想通过 Props 将一个函数传递给一个子组件,子组件将在其逻辑内执行该函数。但是,ESLint 向我返回错误“JSX 道具不应使用函数 react/jsx-no-bind”。我知道这是低效的,因为每次组件重新渲染时都会重新创建该函数。这样做的正确方法是什么?

父组件

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

子组件

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

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

请注意,这不是两个组件的确切代码,它已被简化以删除不相关的代码。

【问题讨论】:

  • 参见 ESLint 文档中的 this。正如它所说,这就是useCallback 的用途
  • Why shouldn't JSX props use arrow functions or bind? 很好地讨论了为什么你不想使用箭头函数作为道具。话虽如此,我完全不同意。您可以使用React.useCallback 来避免在每次重新渲染时重新创建函数。
  • 谢谢两位!你们都说得对,我今天学到了一些新东西。罗宾,如果您可以以答案而不是评论的形式发布此内容,我很乐意投票并接受它作为答案。
  • 内联函数没问题,这个 eslint 规则已经过时了。
  • @krirkrirk 即使没有 useCallback?

标签: javascript reactjs eslint


【解决方案1】:

非常感谢 Robin Zigmond 为我指出了正确的查看位置,该问题已通过 useCallback 挂钩解决。对于任何感兴趣的人,更新后的代码如下所示:

父组件

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

【讨论】:

    猜你喜欢
    • 2016-12-16
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2021-11-22
    • 2020-01-25
    相关资源
    最近更新 更多