无法将 useState() 'set' 函数传递给 grand child

Can't pass useState() 'set' function to grand child

我在尝试让我的 useState 变量工作时遇到问题。我在我的 grandparent 中创建状态,然后将其传递到我的 parent 中。这是我的代码的简化版本:

export function Grandparent(){

return(
    <div>
         const [selectedID, setSelectedID] = useState("0")
         <Parent setSelectedID2={setSelectedID} .../>  //(elipses just mean that I'm passing other params too)
    <div />
)}

Parent:

const Parent = ({setSelectedID2 ...}) => {

   return(
      <div>
          {setSelectedID2("5")}  //works
          <Child setSelectedID3={setSelectedID2} />
      </div>
   )
}

从 parent 我可以像函数一样使用 'setSelectedID2' 并且可以改变状态。但是,当我尝试在下面的 child 组件中使用它时,我收到一条错误消息,指出 'setSelectedID3' 不是函数。我对反应还很陌生,所以我不确定我是否完全遗漏了什么。为什么我可以在 parent 中使用 'set' 函数而不是 child 中的函数,当它们以相同的方式传递时?

Child:

const Child = ({setSelectedID3 ...}) => {
    
    return(
        <div >
            {setSelectedID3("10")} //results in error
        </div>
    );
};

这是一个工作示例,其中包含您在此处列出的所有内容。传递道具并在每个道具中调用函数。

您不需要将 props 命名为 1,2,3..,它们的范围仅限于函数,所以如果它们相同就可以了。

我将 useState 和函数调用移到 return 语句上方,因为那是组件中应该放置的逻辑。 jsx 仅用于处理您的 display/output.

的逻辑

https://codesandbox.io/s/stupefied-tree-uiqw5?file=/src/App.js

此外,我创建了一个带有 onClick 的工作示例,因为这就是您要做的。

https://codesandbox.io/s/compassionate-violet-dt897?file=/src/App.js

import React, { useState } from "react";

export default function App() {
  return <Grandparent />;
}

const Grandparent = () => {
  const [selectedID, setSelectedID] = useState("0");
  return (
    <div>
      {selectedID}
      <Parent setSelectedID={setSelectedID} selectedID={selectedID} />
    </div>
  );
};

const Parent = ({ selectedID, setSelectedID }) => {
  setSelectedID("5");
  return (
    <div>
      {selectedID}
      <Child setSelectedID={setSelectedID} selectedID={selectedID} />
    </div>
  );
};

const Child = ({ selectedID, setSelectedID }) => {
  setSelectedID("10");
  return <div>{selectedID}</div>;
};

输出

10
10
10

在 React 中,您在 components/functions(这是 js 部分)中进行计算,然后您从中 return 得到的是 JSX(这是 html 部分).

export function Grandparent(){

const [selectedID, setSelectedID] = useState("0");

return(
    <div>
         <Parent setSelectedID2={setSelectedID} .../>  //(elipses just mean that I'm passing other params too)
    <div />
)}

您也可以在 JSX 中使用(但不能定义!)一些 js 变量,只要它们可以被 JSX“渲染”(它们不是对象 - 寻找 React 控制台警告)。

这就是你的 React.101 :)

const [selectedID, setSelectedID] = useState("0")

应该在return

外面