【问题标题】:Why do functions inside functional components have no access to props?为什么功能组件内部的功能无法访问道具?
【发布时间】:2021-06-14 23:21:40
【问题描述】:

我想在点击时更改一个字符串,并将该字符串作为道具传递给组件。当我访问函数组件中的道具时,它可以工作,我可以在控制台中看到字符串,但在函数(此处为 testFunction)中它是未定义的。是什么导致了问题以及如何解决?

[这是我的代码的图像

function Diagram({ inputCases, ...props }) {
  const [data, setData] = useState({});

  console.log("from component", inputCases);

  const testFunction = (inputCases) => {
    console.log("From the test Function", inputCases);
  };

  testFunction();

]1

【问题讨论】:

  • 你有 inputCases 作为函数的参数,这将优先于函数范围内传递给组件的 prop。如果要使用组件 props 中的inputCases,请将其从函数的参数中删除。 const testFunction = () => { console.log(inputCases)}
  • 补充一点,由于lexical scoping,没有必要在testFunction 中声明inputCases,它允许您在函数外部使用变量,只要它已在同一个函数中声明范围。

标签: react-hooks react-props react-functional-component


【解决方案1】:

您通过与原始道具名称相同的函数参数覆盖道具。试试这个方法:

//without parameter
const testFunction = () => { 
    console.log("From the test Function", inputCases);
};

【讨论】:

  • 谢谢,你完全正确,没看到。
猜你喜欢
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 2015-09-19
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多