在 React 中将函数从 parent 传递到 child 是否是 anti-pattern,以便 child 可以更新 parent 的状态?

Is it an anti-pattern to pass functions from parent to child in React, so that the child can update the parent's state?

在决定将开箱即用的 setWhateveruseState() 向下传递到 child 与创建自定义 [=19] 之间的考虑因素是什么=] 函数传递给 child,其中 handleWhatever 函数在其中使用 setWhatever(参见下面的案例二)?

毫无疑问,React 是关于将状态从 parent 向下传递到 child。但是在重申这个事实之后,似乎我们总是留下无数的例子,其中一个函数从 parent 传递到 child 是为了让 parent 知道其中的某个值child。我的问题是关于需要将函数传递给 child 的情况。 (如果所有这些情况都被误导并且为了更新 parent 而传递的函数是 anti-pattern 那么知道该怎么做会很有用——全局变量?)。

案例 #1

// Test.js (parent, case one)
import React, { useState } from 'react';
import DetermineValue from './DetermineValue';
const Test = () => {
  const [importantValue, setImportantValue] = useState();
  console.log(importantValue);
  return <DetermineValue setImportantValue={setImportantValue} />;
};
export default Test;

// DetermineValue.js (child, case one)
import React from 'react';
const DetermineValue = ({ setImportantValue }) => {
  return (
    <>
      ...
      onClick={() => {
                setImportantValue('Important Data');
              }}
      ...
    </>
  );
};
export default DetermineValue;

案例 #2

// Test.js (parent, case two)
import React, { useState } from 'react';
import DetermineValue from './DetermineValue';
const Test = () => {
  const [importantValue, setImportantValue] = useState();
  const handleSetImportantValue = (importantValueQuickPass) => {
    setImportantValue(importantValueQuickPass);
  };
  console.log(importantValue);
  return <DetermineValue handleSetImportantValue={handleSetImportantValue} />;
};
export default Test;

// DetermineValue.js (child, case two)
import React from 'react';
const DetermineValue = ({ handleSetImportantValue }) => {
  return (
    <>
      ...
      onClick={() => {
                handleSetImportantValue('Important Data');
              }}
      ...
    </>
  );
};
export default DetermineValue;

如果不包含其他逻辑,我会采用将 setState 传递给子组件的方式。但此警告与子组件调用从父组件传递的 setState 无关。这是关于在 render 阶段调用它。但是您在问题的编辑版本中的代码不应出现此错误。请refer查看有关警告的文档。